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?
As per the documentation, you can access other attributes in the getter by adding a second parameter to the closure:
It appears you'll only able to access other attributes from the models in a custom cast: