Laravel保护列免受不可为空/默认值的质量分配



我正在尝试在我的用户模型中保护"名称"和"电子邮件"属性,因为我不希望我的用户在注册后能够更改它们。

我的用户模型如下所示:

protected $fillable = [
'province',
'city',
'street',
'postal',
'cellphone',
'facebook',
'instagram',
];
protected $guarded = [
'name',
'email',
'password',
'account_type',
'verified_type',
];

注册后,Laravel默认像这样分配这些值:

//Create the user
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'province' => $data['province'],
'city'  => $data['city'],
'street'  => $data['street'],
'postal'  => $data['postal'],
'cellphone' => $data['cellphone'],
'trial_ends_at' => CarbonCarbon::now()->addMonths(3),
'account_type' => $accountType,
]);

但这给我带来了一个错误,因为"name"没有默认值并且不可为空。我了解为什么会出现错误以及如何解决它,但是如果它们没有默认/可为空的属性,我想知道应该如何分配名称和电子邮件。例如,类似这样的内容:

$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->save();
$user->update([
//the rest of the mass assignable values
]);

还是有更简单的方法?

您可以通过将其添加到模型中来完成。

/*
Attribute which are protected from updating.
*/
protected $protected = [
'name', 'email'
];
protected static function boot()
{
parent::boot();
static::saving(function ($model) {
if($model->id){
foreach($model->protected as $attribute){
$model->$attribute = $model->getOriginal($attribute);
}
}
});
}

希望代码是自我解释的。

您可以使用突变器并从受保护的属性中删除名称。 在此处阅读文档

public function setNameAttribute($newName)
{
if(isset($this->name) && $this->name !== null){
throw new Exception;
//or do nothing
} else {
$this->attributes['name'] = $newName;
}
}

并对电子邮件也做同样的事情

最新更新