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, this 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 casts 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 from the database and before saving 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 from the database and setHistoryAttribute function can be used to modify data just before storing in the database. Here I just use the serialize/unserialize function to do the job.

Hope you like this little Laravel trick. Thank you.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.