什么是“质量分配"?在拉拉韦尔(Laravel)是什么意思? [英] What does "Mass Assignment" mean in Laravel?
问题描述
当我浏览有关雄辩的ORM主题部分的Laravel文档时,得到了一个新术语Mass Assignment
.
When I went through Laravel Document about Eloquent ORM topic part, I got a new term Mass Assignment
.
文档显示如何进行批量分配以及fillable
或guarded
属性设置.但是经过这之后,我对Mass Assignment
及其工作原理没有一个清晰的了解.
Document show How to do Mass Assignment and the fillable
or guarded
properties settings. But after went through that, I didn't have a clearly understand about Mass Assignment
and how it works.
根据我过去在CodeIgniter中的经验,我也没有听说过这个词.
In my past experience in CodeIgniter, I also didn't hear about this term.
有人对此有一个简单的解释吗?
Does anyone have a simple explanation about that?
推荐答案
质量分配是在将数组发送给模型创建时,基本上是一次完成模型上的一堆字段,而不是一个接一个地设置,像这样:
Mass assignment is when you send an array to the model creation, basically setting a bunch of fields on the model in a single go, rather than one by one, something like:
$user = new User(request()->all());
(这不是在模型上分别显式设置每个值.)
(This is instead of explicitly setting each value on the model separately.)
您可以使用fillable
保护您希望此字段实际允许更新的字段.
You can use fillable
to protect which fields you want this to actually allow for updating.
您还可以执行以下操作来阻止所有字段可批量分配:
You can also block all fields from being mass-assignable by doing this:
protected $guarded = ['*'];
比方说,在您的用户表中,您有一个user_type
字段,该字段可以具有user/admin值
Let's say in your user table you have a field that is user_type
and that can have values of user / admin
显然,您不希望用户能够更新此值.从理论上讲,如果您使用上述代码,则有人可以将user_type
的新字段注入到表单中,并将"admin"与其他表单数据一起发送,并轻松地将其帐户切换为admin帐户...这是一个坏消息.
Obviously, you don't want users to be able to update this value. In theory, if you used the above code, someone could inject into a form a new field for user_type
and send 'admin' along with the other form data, and easily switch their account to an admin account... bad news.
通过添加:
$fillable = ['name', 'password', 'email'];
您确保使用mass assignment
要更新user_type
值,您需要在模型上显式设置并保存它,如下所示:
To be able to update the user_type
value, you need to explicitly set it on the model and save it, like this:
$user->user_type = 'admin';
$user->save();
这篇关于什么是“质量分配"?在拉拉韦尔(Laravel)是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!