Laravel mutators without a matching database column

448 Views Asked by At

I'm looking at updating my mutators and accessors to the new syntax introduced in Laravel 9 but I can't seem to make it work.

I currently have a model with a MorphMany relationship to a Settings object that acts as a key-value store. As a shorthand I'm using mutators to set a couple of more commonly used settings. Very simplified, it looks like this:

class Item extends Model
    public function setSomeSettingAttribute($value)
    {
        $key = "some_setting";
        Setting::updateOrCreate(
            ["settable_id" => $this->id, "settable_type" => self::class, "key" => $key],
            ["value" => $value]
        );
    }
}

$m = Item::find(1);
// typically in a controller this would be $request->all()
$arr = ["some_setting" => 234];
$m->update($arr);

This works fine and the setting is updated. The important thing to note is that there is no column in the database named some_setting.


In the new code, it seems like the mutator should look like this:

public function someSetting(): Attribute
{
    $key = "some_setting";
    return Attribute::make(
        set: function ($value) use ($key): void {
            Setting::updateOrCreate(
                ["settable_id" => $this->id, "settable_type" => self::class, "key" => $key],
                ["value" => $value]
            );
        }
    );
}

But this is not working; Laravel is attempting to insert something into the some_setting column, resulting in an SQL "column not found" error.

Is there a way around this that doesn't involve editing all my controller code to remove the fake columns? Or, if not, is the old mutator syntax deprecated in any way?

0

There are 0 best solutions below