Laravel 8, Eloquent mutator does not called at all

432 views Asked by At

I created a mutator in model class as follows:

public function setFileDataAttribute($value)
    {
        if (is_null($value)) {
            $value = [];
        }

        return $value;
    }

The corresponding field is : file_data. Catsts and fillables are also set:

protected $casts = [
        "created_at" => "datetime:Y-m-d H:i",
        "file_data" => "array",
    ];

protected $attributes = [
     "file_data" => [],
    ];

I have really tried everything, but it is simply not called (I have dd-ed it - nothing) Anyone, any idea?


Update: The class is (simplified):

class XXX extends Model
{
    use HasFactory;
    use SoftDeletes;

    protected $fillable = [
        "name",
        "cost_type",
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
       
        "file_data" => "array",
    ];

    protected $attributes = [
        "file_data" => [],
    ];

    public function setFileDataAttribute($value)
    {
        if (is_null($value)) {
            $value = [];
        }

        return $value;
    }

   
}
1

There are 1 answers

1
Akmal Arzhang On

I think you are missing something here; You need to actually set the value, using $this keyword. For example:

public function setFileDataAttribute($value)
{
  if (is_null($value)) {
     $value = [];
  }

  $this->attributes['file_data'] = $value;
}

Or better:

$this->attributes['file_data'] = is_null($value) ? [] : $value;

There are differences between accessor and mutators. If you want to use accessor, you can use get keyword instead of set and your approach is just fine, however, if you want to mutate it when you are inserting or updating the database, you need to assign it to the attribute.

Accessor: An accessor transforms an Eloquent attribute value when it is accessed.

Mutator: A mutator transforms an Eloquent attribute value when it is set.

More at: https://laravel.com/docs/8.x/eloquent-mutators#defining-a-mutator

I hope it helps.