Eloquent Model JSON Serialization and Deserialization

Awhile back I needed to save an Eloquent model to the DB so that I might compute a delta later on. Json serves this purpose nicely since the json data type is now natively supported in many languages.

One could do this manually but, fortunately, Laravel makes this easy on us. We can utilize model mutators to dynamically convert the input and output of a specific database column.

For example, say we want to save a passed in model as json and that the column that we want to save to is called json:

/**
 * @param YourModel $model
 */
public function setJsonAttribute(YourModel $model)
{
    // Eloquent Models implement ArrayIterator so that allows us to access the attributes as an array.
    // When using a mutator, you cannot use $this->json since that is part of the functionality that we are
    // defining here.
    $this->attributes['json'] = $model->toJson();
}

This allows us to set the attribute like so:

// This will convert the $modelToSave to json and then save that json to the database
$model->json = $modelToSave;

That way the model will automatically be saved to json in the database. The retrieval is a little bit trickier:

/**
 * @return YourModel
 */
public function getJsonAttribute()
{
    /** @var YourModel $model */
    $model = new YourModel();

    // retrieve the model serialized as json
    $jsonToConvert = $this->attributes['json'];

    // This converts the json to an array
    $modelArray = $model->fromJson($jsonToConvert);

    // We now create a new instance of YourModel from that array
    return $model->newInstance($modelArray);
}

Now anytime that we call $model->json we will get an instance of YourModel. This is quite convenient and allows us to simplify our code.

You will notice that I am using several Eloquent methods that are not commonly used. I recommend taking a look through the Eloquent model documentation since it shows you quite a few methods that might come in handy later.

Written on February 21, 2016