Laravel Eloquent - Serialization to array and Json

When working with API in Laravel or similar, often you need to get query results to array or json instead of model object. Laravel provides simple ways to convert query results in array or json.

Convert to Array

Laravel convert all model and relationship query to array with toArray method. 


use App\Models\Post;

$posts = Post::first()

You can also convert Laravel collection to array with toArray method.

$posts = Post::all();

$posts = $posts->toArray();

Convert to Json

To convert Laravel model query to Json, you can use toJson method. It works same way as toArray method for array.


use App\Models\Post;

$post = Post::where('id', 1)

Second way is you may type cast the model query, which converts all model query to Json automatically.

$post = (string) Post::where('id', 1)

I hope this small article find you helpful.