Laravel Eloquent - Serialization to array and Json

  2 weeks ago     Views:  100  
Hardik Savani
1 Follows


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. 

<?php

use App\Models\Post;

$posts = Post::first()
    ->toArray();

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.

<?php

use App\Models\Post;

$post = Post::where('id', 1)
    ->toJson();

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

$post = (string) Post::where('id', 1)
	->get();

I hope this small article find you helpful.


Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

OR

No Comments