laravel model mutators not accessing the defined field

2.7k Views Asked by At

I am trying to define a model mutator

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Custom_fields extends Model
{
    protected $table = 'custom_fields';

    public function setContentAttribute($value){
        return unserialize($value);
    }
}

and on test controller, tried

Custom_fields::all()[0]->content;

Unfortunately, it is not working; the value is still not an array (serialize)

I want to access the field content and unserialize the value of the field so I can get an array automatically on retrieve, but it's not working.

1

There are 1 best solutions below

2
On BEST ANSWER

You're trying to "get an array automatically on retrieve" with a method called setContentAttribute. You are confusing accessors and mutators. As the method name implies, the mutator is called when you set the content attribute.

To create an accessor that is called when you get the content attribute:

public function getContentAttribute($value)
{
    return unserialize($value);
}

Likely if this data is to be stored in a serialized form you want your mutator to look like this:

public function setContentAttribute($value)
{
    $this->attributes["content"] = serialize($value);
}

But really, you should not be using these serialization functions at all. Laravel can natively convert objects to JSON for storage in a database. Simply define the property in your model's $casts property and data will be converted automatically when getting or setting the property.

protected $casts = [
    "content" => "array",
];