How can i convert this Laravel collection array to json format like below.
//All records from users table.
$users = DB::table('users')->get();
// Required json format.
return '{
"data": [
{
"DT_RowId": "row_1",
"id": "Tiger",
"clear": "Nixon",
"fsssf": "System Architect",
"tex": "[email protected]",
"created_at": "Edinburgh",
"updated_at": "Edinburgh"
},
{
"DT_RowId": "row_2",
"id": "Tiger",
"clear": "Nixon",
"fsssf": "System Architect",
"tex": "[email protected]",
"created_at": "Edinburgh",
"updated_at": "Edinburgh"
}
],
"options": [],
"files": []
}';
Sorry for the basic question,but i am unable to convert this into this jso.
You can use toJson(),to convert the collection to json object.
Laravel JSON is a small package that makes encoding and decoding JSON a breeze with exceptions thrown on error immediately: A simple wrapper around json_encode() and json_decode() for catching any errors without executing json_last_error() .
The json_decode() function can return a value encoded in JSON in appropriate PHP type. The values true, false, and null is returned as TRUE, FALSE, and NULL respectively. The NULL is returned if JSON can't be decoded or if the encoded data is deeper than the recursion limit.
JSON is based on two basic structures namely Objects and Arrays. Parsing JSON data in PHP: There are built-in functions in PHP for both encoding and decoding JSON data. These functions are json_encode() and json_decode(). These functions works only with UTF-8 encoded string.
Today, we will be looking at how we can use the toJson () method to convert a Laravel Collection to JSON format. The toJson () method will return the JSON encoded version of the data stored in a Laravel Collection. Under the hood Laravel, apply the native json_encode () method of PHP.
here is sample code to convert collections object to array in Laravel. $products=App\Product::all(); return$products->toArray(); $products = App\Product::all();return $products->toArray();
You can also cast a collection or model to string. here is sample code to convert collections object to array in Laravel. $products=App\Product::all();
The signature of toJson () the method in the laravel collection is something like the below code in the laravel application. This is how toJson () can be used in the laravel eloquent model. This is how toJson () the method can be used to laravel collection.
Have a look at the documentation.
You can use toJson(),to convert the collection to json object.
$users = DB::table('users')->get()->toJson();
dd($users);
You can also can do this in simple php way by using json_encode function
$users = json_encode($users);
Have a look at this link
Greetings and happy coding!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With