Search code examples
laravellaravel-8laravel-9

Laravel Accessor setting numbers times 100 on set and divide on get


I want to store shipping costs in my database as Integers and Doubles are giving. So on Get I will divide the value by 100 and when Set I do the values times 100.

But why is this not working?

protected function shippingcosts(): Attribute
{
    return Attribute::make(
        get: fn ($value, $attributes) => [
            'Small' => is_numeric($attributes['Small']) ? ($attributes['Small'] / 100) : 0,
            'Large' => is_numeric($attributes['Large']) ? ($attributes['Large'] / 100) : 0,
            'BulkSizeForLarge' => $attributes['BulkSizeForLarge'],
        ],
        set: fn ($value) => [
            'Small' => is_numeric($value['Small']) ? ($value['Small'] * 100) : 0,
            'Large' => is_numeric($value['Large']) ? ($value['Large'] * 100) : 0,
            'BulkSizeForLarge' => $value['BulkSizeForLarge'],
        ],
    );
}

In my Model it is stored in a JSON column in the database and casting is set to:

  protected $casts = [
        'shippingcosts' => 'collection',
    ];

As far as I'm concerned when reading the Laravel docs this should work, but it doesn't.

What am I missing?


Solution

  • protected function shippingcosts(): Attribute
    {
        return Attribute::make(
                get: fn ($value, $attributes) => [
                    'Small' => is_numeric($value['Small']) ? ($value['Small'] / 100) : 0,
                    'Large' => is_numeric($value['Large']) ? ($value['Large'] / 100) : 0,
                    'BulkSizeForLarge' => $value['BulkSizeForLarge'],
                ],
                set: fn ($value) => [
                    'Small' => is_numeric($value['Small']) ? ($value['Small'] * 100) : 0,
                    'Large' => is_numeric($value['Large']) ? ($value['Large'] * 100) : 0,
                    'BulkSizeForLarge' => $value['BulkSizeForLarge'],
                ],
        );
    }
    

    Use $value instead of $attribute,