Laravel Eloquent - Serialization to array and Json
1 year ago By Hardik Savani 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
<?php use App\Models\Post; $posts = Post::first() ->toArray();
You can also convert Laravel collection to array with
$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.
Copyright 2023 HackTheStuff