Laravel 9 mutators for json field

50 Views Asked by At

I have a jsonb field in DB named attributes and I need to add some default values to the object. So I tried to make mutator for this property. Incoming value is associative array and I want to save it as json. The code looks like this

    protected function attributes(): Attribute
    {
        return Attribute::make(
            get: function ($value) {
                Log::info('get');
                Log::info($value);
                return $value;
            },
            set: function($value) {
                // Set default values for below attributes
                Log::info('set');
                Log::info($value);
                $value["icon"] = $value['icon'] ?? null;
                $value["overlay"] = $value['overlay'] ?? null;
                $value["category"] = $value['category'] ?? null;
                $value["display_name"] = $value['display_name'] ?? null;
                $value["use_tenant_icon"] = $value['use_tenant_icon'] ?? false;
                $value["map_rotation_angle"] = $value['map_rotation_angle'] ?? false;

                Log::info($value);
                return $value;
            },
        );
    }

All logs looks fine as I expect, but this throws me an error:

"PDOException: SQLSTATE[42703]: Undefined column: 7 ERROR: column "icon" of relation "entities" does not exist

I dont understand why Laravel want to insert return value as separate columns and not as one value for column attributes.

0

There are 0 best solutions below