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.
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();
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.
How to Convert JS Object to JSON StringUse the JSON.stringify() Method You c...
Django - How to Create Custom Login PageWithin this article we will look at how...
How to toggle text inside and element on click using jQueryUse the jQuery text() method You can...
Laravel Eloquent whereIn Method Query ExampleSometimes you might want to get records...