When writing the API, the data is generally transmitted in JSON format, and no objects can be used directly. At this time, the serialization of data conversion is very important, eloquent provides a very convenient method and conventions, not only can be converted, but also control the key values inside.
Basic usage transforms a model into arrays
$user = App\User::with(‘roles‘)->first();
return $user->toArray();
Convert a model into an array;
$users = App\User::all();
return $users->toArray();
Convert collection into arrays;
Convert the model to JSON
$user = App\User::find(1);
return $user->toJson();
This is a manual function;
If you return directly to a model or collection, the system will automatically cast it into JSON:
Route::get(‘users‘, function () {
return App\User::all();
});
You can test the results with a route.
Hide some of the properties in JSON
A field like password, in fact, does not want to appear in the JSON for others to see, then you can hide it
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $hidden = [‘password‘];
}
This is the blacklist;
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $visible = [‘first_name‘, ‘last_name‘];
}
This is a white list;
The document is written in red letters:
Note: When hiding relationships, use the relationship‘s method name, not its dynamic property name.
Because some tables are related to queries, you can hide these tables, but fill in the filter field above, do not fill in the field of the related table, but fill in the model of the relationship between the method, so that the entire table can be hidden, if you want to hide the related tables of some fields, then to the association table to hide. (I wanted to write an example, my wife told me to go to breakfast, not to write.) )
Add some of the properties in the JSON
Just said to remove the attribute, obviously sometimes you also need to manually add some properties:
The first step is to add a accessor:
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function getIsAdminAttribute()
{
//return $this->attributes[‘admin‘] == ‘yes‘;
//官网是这样写的,何必增加理解难度,让人混淆呢,真是的;
//我简写成这样了
return ‘yes‘;
}
}
In the second step, add the added fields to the $appends array:
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function getIsAdminAttribute()
{
//return $this->attributes[‘admin‘] == ‘yes‘;
//官网是这样写的,何必增加理解难度,让人混淆呢,真是的;
//我简写成这样了
return ‘yes‘;
}
protected $appends = [‘is_admin‘];
}
Okay, there's one more in the JSON.is_admin: "yes"
Laravel 5.1 Document Guide--eloquent: Serialization of Model objects