If you take a look at the code into the model you will see two methods: toArray
and toJson
. These two methods are the ones that make the magic happen.
// from the IlluminateDatabaseEloquentModel class ... /** * Convert the model instance to an array. * * @return array */ public function toArray() { $attributes = $this->attributesToArray(); return array_merge($attributes, $this->relationsToArray()); } ... /** * Convert the model instance to JSON. * * @param int $options * @return string */ public function toJson($options = 0) { return json_encode($this->toArray(), $options); }
Note
You can also see that the second method uses the first. If you don’t fear big files, I suggest you to take a deeper look at all the methods in this class. You will see some awesome examples of code reusing and function writing. In this chapter, we are just scratching the surface.
You can convert both single models and model collections to arrays or JSON:
return AppBook::all()->toJson(); // or ... return AppBook::where('title', 'LIKE', 'My%')->get()->toArray(); // or return AppBook::find(1)->toJson();
Obviously, for security reasons, you can choose to mark some specific fields as hidden
. They will not be shown when the record is converted to array or JSON.
<?php namespace App; use IlluminateDatabaseEloquentModel; class User extends Model { protected $hidden = ['password', 'credit_card_number']; }
In this case, with hidden
, we specified a blacklist. You can also define a whitelist with the visible
property.
<?php namespace App; use IlluminateDatabaseEloquentModel; class User extends Model { protected $visible = ['first_name', 'last_name']; }
Comments