access to create array in laravel Mutator

291 Views Asked by At

I want to create a new user by calling create method like this:

User::create([
      'phone_number'  => '09121231212',
      'country_code'  => 'ir',
]);

I want to change the phone number format to international phone number format by Propaganistas\LaravelPhone package in phone number mutator like this:

    public function phoneNumber(): Attribute
    {
        return Attribute::make(
            get: fn ($value) => (new PhoneNumber($value, $this->country_code))->formatNational(),
            set: fn ($value) => (new PhoneNumber($value, $this->country_code))->formatE164(),
        );
    }

the problem is that in the phone_number mutator(set) I don't have access to the country_code that is defined in create array so I can not change the phone_number format before inserting it into the database.

also, I don't want to merge country_code to request and get it in the mutator. is there any better solution?

1

There are 1 best solutions below

5
Dan On

As per the documentation, you can access other attributes in the getter by adding a second parameter to the closure:

public function phoneNumber(): Attribute
{
    return Attribute::make(
        get: fn ($value, $attributes) => (new PhoneNumber($value, $attributes['country_code']))->formatNational(),
    );
}

It appears you'll only able to access other attributes from the models in a custom cast:

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;

class PhoneNumberCast implements CastsAttributes
{
    public function get($model, $key, $value, $attributes)
    {
        return (new PhoneNumber($value, $attributes['country_code']))
            ->formatNational();
    }

    public function set($model, $key, $value, $attributes)
    {
        return (new PhoneNumber($value, $attributes['country_code']))
            ->formatE164();
    }
}