support@codebucket.net

What is eloquent serialization in Laravel

What is eloquent serialization in Laravel

K. M. Shawkat Zamil | December 25, 2022

Hello developers,

 

In your development journey, sometimes you want to convert your data to an array or JSON. This is very much needed when you make APIs using Laravel. Eloquent includes convenient methods for making these conversions. It also controls which attributes are included in the serialized representation of your models. We will cover the basic things you might know about Eloquent Serialization.

 

Serializing Models & Collection (Serializing To Arrays)

 

In the results, to convert a model and its loaded relationships to an array, you should use toArray method. This will make your data into arrays. The code is given below:

 

 

use App\Models\Sample;
 
$sample = Sample::with('test')->first();
 
return $sample->toArray();

 

If you want to convert only the model attributes to an array but not its relationships, you should use attributesToArray, the below code:

 

$sample = Sample::first();
 
return $sample->attributesToArray();

 

If you want to convert the entire collection of models to an array, you can use toArray by the following code:

 

$samples = Sample::all();
 
return $samples->toArray();

 

Serializing Models & Collection (Serializing To JSON)

 

 In the results, to convert a model to JSON, you should use toJson method. Like toArray, the toJson will convert all attributes and relations converted to JSON. Here I use Sample Model. Code this listed below:

 

use App\Models\Sample;
 
$sample = Sample::find(1);
 
return $sample->toJson();
 
or

return $sample->toJson(JSON_PRETTY_PRINT);

 

Besides, you can cast your data to a string, it will automatically call the toJson method. 

 

return (string) Sample::find(1);

 

You can return Eloquent objects directly from your application's routes or controllers. Laravel will automatically serialize your Eloquent models and collections to JSON when they are returned from routes or controllers.

 

Route::get('samples', function () {
    return Sample::all();
});

 

 

Hiding Attributes from JSON

 

Sometimes, you want to hide your attributes from users such as passwords. For that, you can use $hidden property to your models. The model will look like the below code if you use hidden property:

 

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
 
class Sample extends Model
{
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = ['password'];
}

 

You can use visible property to allow attributes to the list. All attributes that are not present in the $visible array will be hidden when the model is converted to an array of JSON.

 

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
 
class Sample extends Model
{
    /**
     * The attributes that should be visible in arrays.
     *
     * @var array
     */
    protected $visible = ['test1', 'test2'];
}

 

If you want to make it hidden or visible temporarily, you can use makeHidden or makeVisible.

 

return $sample->makeVisible('attribute')->toArray();




return $sample->makeHidden('attribute')->toArray();

 

Appending Values To JSON

 

If you want to add new attributes to arrays or JSON that do not have in the database, you should follow these steps. First, write the following code in the model:

 

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
 
class Sample extends Model
{
    /**
     * Determine if the user is an administrator.
     *
     * @return \Illuminate\Database\Eloquent\Casts\Attribute
     */
    protected function newColumn(): Attribute
    {
        return new Attribute(
            get: fn () => 'yes',
        );
    }
}

 

After that, you should use the append property to the model. Note that, Attributes names are referenced using their "snake case" serialized representation, even though the method is defined using "camel case"

 

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
 
class Sample extends Model
{
    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = ['new_column'];
}

 

Also, the append method can use the run time.

 

return $sample->append('new_column')->toArray();
 
return $sample->setAppends(['new_column'])->toArray();

 

That's all for today. Hope this might help in your journey of development.

 

Read More: How to Redirect www URL to Non-www URL

K. M. Shawkat Zamil

K. M. Shawkat Zamil

Senior Software Engineer

I am a Senior Software Engineer in a reputed company in Bangladesh. I am a big fan of Laravel, PHP Programming, MSSQL Server, MySql, JavaScript, and lots more. I love to help people who are especially eager to learn. I believe in patience and motivation.