06.10.2016 Views

laravel-5

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Eloquent: Serialization<br />

• Introduction<br />

• Basic Usage<br />

• Hiding Attributes From JSON<br />

• Appending Values To JSON<br />

Introduction<br />

When building JSON APIs, you will often need to convert your models and relationships to arrays<br />

or JSON. Eloquent includes convenient methods for making these conversions, as well as controlling<br />

which attributes are included in your serializations.<br />

Basic Usage<br />

Converting A Model To An Array<br />

To convert a model and its loaded relationships to an array, you may use the toArray method. This<br />

method is recursive, so all attributes and all relations (including the relations of relations) will be<br />

converted to arrays:<br />

1 $user = App\User::with('roles')->first();<br />

2<br />

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

You may also convert collections to arrays:<br />

1 $users = App\User::all();<br />

2<br />

3 return $users->toArray();<br />

614

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

Saved successfully!

Ooh no, something went wrong!