How To Do Serialization To JSON In Laravel With Example

admin_img Posted By Bajarangi soft , Posted On 10-09-2020

When building JSON APIs, you will often need to convert your models and relationships to arrays or JSON. Eloquent includes convenient methods for making these conversions, as well as controlling which attributes are included in your serializations.

How To Do Serialization To JSON In Laravel With Example

Serializing To JSON

To convert a model to JSON, you should use the toJson method. Like toArray, the toJson method is recursive, so all attributes and relations will be converted to JSON. You may also specify JSON encoding options supported by PHP:

For Example(1)


1.Create route in web.php file

Route::get('/SerializationToJSON', 'demoController@SerializationToJSON')->name('SerializationToJSON');


2.Create demoController by using below command 

php artisan make:controller demoController


3.Implement code in demo controller as below

<?php

namespace App\Http\Controllers;
use App\Http\Requests;
use App\User;

class demoController extends AppBaseController
{
    public function SerializationToJSON()
    {
        $user = User::find(1);

       // return $user->toJson();

        return $user->toJson(JSON_PRETTY_PRINT);
    }
}

In above example get specified data using user id from user table using model name and display in JSON encoding

Alternatively, you may cast a model or collection to a string, which will automatically call the toJson method on the model or collection:

 
$user = App\User::find(1);

return (string) $user;


Since models and collections are converted to JSON when cast to a string, you can return Eloquent objects directly from your application's routes or controllers:
 

Route::get('users', function () {
return App\User::all();
});


Relationships

When an Eloquent model is converted to JSON, its loaded relationships will automatically be included as attributes on the JSON object. Also, though Eloquent relationship methods are defined using "camel case", a relationship's JSON attribute will be "snake case".

Related Post