2 min read

PHP serialization / unserialization in Laravel using Accessors & Mutators

It is a very common use case to store/retrieve array type data to/from the database by using PHP’s serialize/unserialize function. When this data is coming back and forth from JSON format, these 2 functions quickly do the conversion from array to database storable string format and vice versa.

In plain PHP code, to get the string just pass the array as an argument in the serialize() function. For the opposite, pass the string as an argument in the unserialize() function. That’s it. When using Laravel, you can do it just like plain PHP. But there are some ways in which this conversation can be done automatically simply by doing a little modification to your model.

For example, Let’s say, we have a Patient Model and there is a history attribute where we would like to store a big array of histories.

The easiest way – Array & JSON casting

In the Patient Model, we just have to declare a protected cast array with the attribute and type of cast as a key and value of the array.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Patient extends Model
{

    protected $casts = [
        'history' => 'array',
    ];
}

That’s all. When you save your model, an array will be automatically converted into a serialized string and when retrieve serialized string will be automatically converted into an array.

The flexible way – Accessors & Mutators

Accessors and Mutators are very good options for modifying the data after retrieving it from the database and before saving it to the database. To achieve this, we just have to define two additional functions in our Patient Model – One for Accessor, the other for Mutator.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Patient extends Model
{
    public function getHistoryAttribute($value)
    {
        return unserialize($value);
    }

    public function setHistoryAttribute($value)
    {
        $this->attributes['history'] = serialize($value);
    }
}

You can see the getHistoryAttribute function can be used to modify just after retrieving it from the database and the setHistoryAttribute function can be used to modify data just before storing it in the database. Here I just use the serialize/unserialize function to do the job.

Hope you like this little Laravel trick. Thank you.