Serialize model data into arrays or JSON


brief introduction

When building JSON APIs, you often need to convert models and associations into arrays or JSON. Eloquent provides convenient methods to implement these transformations and control which properties are included in serialization.

Serialization Model&Collection

Serialized as an array

To convert the model and its loaded Association Is an array, you can use toArray method. This method is recursive, so all attributes and their associated object attributes (including associated associations) will be converted into arrays:

 $user = App\User::with('roles')->first(); return $user->toArray();

You can also convert the entire model aggregate Is an array:

 $users = App\User::all(); return $users->toArray();

Serialized as JSON

To convert the model to JSON, you can use toJson Methods, and toArray Same, toJson The method is also recursive. All attributes and their associated attributes will be converted into JSON:

 $user = App\User::find(1); return $user->toJson();

You can also convert models or collections into strings, which will automatically call toJson method:

 $user = App\User::find(1); return (string) $user;

Since models and collections will be converted into JSON when they are converted into strings, you can directly return Eloquent objects from the application route or controller:

 Route::get('users',function(){ return App\User::all(); });

Hide attributes in JSON

Sometimes you want to hide some attributes, such as passwords, in the model array or JSON display. To implement this function, set the $hidden Properties:

 <? php namespace App; use Illuminate\Database\Eloquent\Model; class User extends Model { /** *Properties hidden in the array * * @var array */ protected $hidden = ['password']; }
Note: If you want to hide the association, use the method name of the association instead of the dynamic attribute name.

In addition, you can use the $visible Property to define the white list of model array and JSON displayed properties:

 <? php namespace App; use Illuminate\Database\Eloquent\Model; class User extends Model { /** *Properties displayed in the array * * @var array */ protected $visible = ['first_name', 'last_name']; }

Temporary exposure hidden attribute

If you want to temporarily display hidden attributes in a specific model, you can use makeVisible Method, which returns the model instance by calling the method chain:

 return $user->makeVisible('attribute')->toArray();

Similarly, if you want to hide some displayed properties on a given model instance, you can use makeHidden method:

 return $user->makeHidden('attribute')->toArray();

Append value to JSON

Sometimes, you need to add fields that are not in the database to the array. To implement this function, first define a Accessor

 <? php namespace App; use Illuminate\Database\Eloquent\Model; class User extends Model { /** *Get administrator ID for user * * @return bool */ public function getIsAdminAttribute() { return $this->attributes['admin'] == 'yes'; } }

After the accessor is defined, add the field name to the appends Property. It should be noted that although accessors are defined in the form of "camera case", attribute names are usually referenced in the form of "snake case":

 <? php namespace App; use Illuminate\Database\Eloquent\Model; class User extends Model { /** *Accessor appended to model array form * * @var array */ protected $appends = ['is_admin']; }

Fields are added to appends After the list, it will be included in the model array and JSON, appends The properties in the array also follow the visible and hidden set up.

Append at runtime

You can use it on a single model append Method to append attributes, or you can use the setAppends Method covers the entire appended attribute array for a given model:

 return $user->append('is_admin')->toArray(); return $user->setAppends(['is_admin'])->toArray();

Date Serialization

Larravel extends Carbon The date library provides convenient customization for JSON serialization format of Carbon. To customize how all Carbon dates are serialized in the entire application, you can use Carbon::serializeUsing method. serializeUsing Method receives a closure that returns a date in string form for JSON serialization:

 <? php namespace App\Providers; use Illuminate\Support\Carbon; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { /** * Perform post-registration booting of services. * * @return void */ public function boot() { Carbon::serializeUsing(function ($carbon) { return $carbon->format('U'); }); } /** * Register bindings in the container. * * @return void */ public function register() { // } }

give the thumbs-up Cancel Like Collection Cancel Collection

<<Previous: API resource class: bridge between the model and JSON API

>>Next: Use Artisan to build powerful console applications