SigalZ's avatar

how to set an accessor by parameter

Hello,

Using Laravel 10, I have a table with a column:

shipping_method tinyInt

I want to set this column by a string or get it and change it to a string.

e.g. if the column holds 2 it should return 'Courier' if I set it to 'Courier' it should set to 2.

Not sure how to do it as an accessor:

What should I do in the Model accessor function?

protected static $shipping_methods = [        
        1 => 'Post Office',
        2 => 'Courier',
        3 => 'Collect',
        4 => 'Highland Delivery',
        5 => 'Delivery by Sales Rep'
];

protected function shippingMethod(): Attribute
    {
        return Attribute::make(
            set: fn (string $value) => //What to do here?
            get: fn ($value) => //What to do here?            
        );
    }

Thank you

0 likes
4 replies
s4muel's avatar
s4muel
Best Answer
Level 50

you can achieve it like this:

protected function shippingMethod(): Attribute
{
    return Attribute::make(
        set: function (string $value) {
            // Flip the array to get the key by the value
            $map = array_flip(self::$shipping_methods); //flip array so the key can be easily get from value
            return $map[$value] ?? null; //fallback to null? or throw exception?
        },
        get: function ($value) {
            return self::$shipping_methods[$value] ?? null; //fallback to null? or throw exception?
        }
    );
}

but i would suggest to use Enum casting instead https://laravel.com/docs/10.x/eloquent-mutators#enum-casting

1 like
SigalZ's avatar

@s4muel Thank you very much. I changed the code to Enum, but would you mind explaining why do you think it is better?

1 like

Please or to participate in this conversation.