Laravel Eloquent Serialization to array and Json

  2250 views   6 months ago Laravel

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 article find you helpful.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]