問題描述
當我瀏覽有關 Eloquent ORM 主題部分的 Laravel 文檔時,我得到了一個新術語批量分配".
When I went through Laravel Document about Eloquent ORM topic part, I got a new term "Mass Assignment".
文檔顯示如何進行批量分配和 $fillable
或 $guarded
屬性設置.但是經歷了那之后,我對批量分配"并沒有清楚的了解.以及它是如何工作的.
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 是當你發送一個數組到模型創建時,基本上是一次性在模型上設置一堆字段,而不是一個一個,類似:
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"與其他表單數據一起發送,然后輕松地將他們的帳戶切換到管理員帳戶... 壞消息.
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
You are ensuring that only those values can be updated using 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 中是什么意思?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!