What does “Mass Assignment” mean in Laravel?

匿名 (未验证) 提交于 2019-12-03 01:58:03

问题:

When I went through Laravel Document about Eloquent ORM topic part, I got a new term 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.

In my past experience in CodeIgniter, I also didn't hear about this term.

Does anyone have a simple explanation about that?

回答1:

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(Input::all()); 

(This is instead of explicitly setting each value on the model separately.)

You can use fillable to protect which fields you want this to actually allow for updating.

Let's say in your user table you have a field that is user_type and that can have values of user / 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.

By adding:

$fillable = array('name', 'password', 'email'); 

You are ensuring that only those values can be updated using mass assignment

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(); 


回答2:

Mass assignment means you are filling a row with more than one column using an array of data. (somewhat of a shortcut instead of manually building the array) using Input::all().

Technically just from the top of my head. Fillable means what columns in the table are allowed to be inserted, guarded means the model can't insert to that particular column.

Notice that when you try to do a mass assignment with like, insert to a column named "secret", and you have specified that it is guarded, you can try to insert to it via the model, but it will never really get inserted into the database.

This is for security, and protection on your table when using the model. Mass assignment seems to be just a notice or warning that you didn't tell the model which are fillable and guarded and makes it vulnerable to some kind of attacks.



回答3:

UPDATE

For Laravel 5.x you can refer to the latest doc mass assignment

OR

A well detailed explanation on when to use fillable or guarded



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!