29.07.2016 Views

laravel-5

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Eloquent: Serialization 481<br />

Converting A Model To JSON<br />

To convert a model to JSON, you may use the toJson method. Like toArray, the toJson method is<br />

recursive, so all attributes and relations will be converted to JSON:<br />

.<br />

1 $user = App\User::find(1);<br />

2<br />

3 return $user->toJson();<br />

Alternatively, you may cast a model or collection to a string, which will automatically call the toJson<br />

method:<br />

.<br />

1 $user = App\User::find(1);<br />

2<br />

3 return (string) $user;<br />

Since models and collections are converted to JSON when cast to a string, you can return Eloquent<br />

objects directly from your application’s routes or controllers:<br />

.<br />

1 Route::get('users', function () {<br />

2 return App\User::all();<br />

3 });<br />

Hiding Attributes From JSON<br />

Sometimes you may wish to limit the attributes, such as passwords, that are included in your model’s<br />

array or JSON representation. To do so, add a $hidden property definition to your model:<br />

.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!