Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
385 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.)

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 = ['*'];

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 = ['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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...