Laravel Mutator处理手机号时无法获取create数组内country_code的解决方案
问题分析
调用User::create()创建用户时,phone_number的set mutator执行时机早于country_code的属性赋值,导致mutator中$this->country_code无法获取到传入的国家码,进而无法完成手机号的国际格式转换。
解决方案
方案1:利用模型creating事件(推荐)
在模型即将创建前触发的creating事件中,模型已完成所有属性的赋值,此时可以安全获取country_code并格式化手机号:
// User 模型中 protected static function boot() { parent::boot(); static::creating(function ($user) { if ($user->country_code && $user->phone_number) { $user->phone_number = (new PhoneNumber($user->phone_number, $user->country_code))->formatE164(); } }); }
方案2:自定义静态创建方法
在User模型中封装一个专用创建方法,提前处理手机号格式后再调用原生create:
// User 模型中 public static function createWithFormattedPhone(array $attributes) { if (isset($attributes['phone_number'], $attributes['country_code'])) { $attributes['phone_number'] = (new PhoneNumber($attributes['phone_number'], $attributes['country_code']))->formatE164(); } return static::create($attributes); }
使用方式:
User::createWithFormattedPhone([ 'phone_number' => '09121231212', 'country_code' => 'ir', ]);
方案3:调整属性赋值顺序(不推荐)
强制让country_code先于phone_number被赋值,依赖数组键的顺序实现mutator获取国家码,但这种方式稳定性差,一旦属性顺序变更就会失效:
User::create([ 'country_code' => 'ir', // 先赋值国家码 'phone_number' => '09121231212', // 再赋值手机号 ]);
内容的提问来源于stack exchange,提问作者sajadsholi
相关产品推荐
相关产品推荐

