Database: Model Serialization
Introduction
When building JSON APIs, you will often need to convert your models and relationships to arrays or JSON. Models includes convenient methods for making these conversions, as well as controlling which attributes are included in your serializations.
Basic usage
Converting a model to an array
To convert a model and its loaded relationships to an array, you may use the toArray
method. This method is recursive, so all attributes and all relations (including the relations of relations) will be converted to arrays:
You may also convert collections to arrays:
Converting a model to JSON
To convert a model to JSON, you may use the toJson
method. Like toArray
, the toJson
method is recursive, so all attributes and relations will be converted to JSON:
Alternatively, you may cast a model or collection to a string, which will automatically call the toJson
method:
Since models and collections are converted to JSON when cast to a string, you can return Model objects directly from your application's routes, AJAX handlers or controllers:
Hiding attributes from JSON
Sometimes you may wish to limit the attributes, such as passwords, that are included in your model's array or JSON representation. To do so, add a $hidden
property definition to your model:
Alternatively, you may use the $visible
property to define a white-list of attributes that should be included in your model's array and JSON representation:
Appending values to JSON
Occasionally, you may need to add array attributes that do not have a corresponding column in your database. To do so, first define an accessor for the value:
Once you have created the accessor, add the attribute name to the appends
property on the model:
Once the attribute has been added to the appends
list, it will be included in both the model's array and JSON forms. Attributes in the appends
array will also respect the visible
and hidden
settings configured on the model.