What does "Mass Assignment" mean in Laravel?
Solution 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(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();
Solution 2:
Mass assignment is a process of sending an array of data that will be saved to the specified model at once. In general, you don’t need to save data on your model on one by one basis, but rather in a single process.
Mass assignment is good, but there are certain security problems behind it. What if someone passes a value to the model and without protection they can definitely modify all fields including the ID. That’s not good.
Let's say you have 'students' table, with fields "student_type, first_name, last_name”. You may want to mass assign "first_name, last_name" but you want to protect student_type from being directly changed. That’s where fillable and guarded take place.
Fillable lets you specify which fields are mass-assignable in your model, you can do it by adding the special variable $fillable
to the model. So in the model:
class Student extends Model {
protected $fillable = ['first_name', 'last_name']; //only the field names inside the array can be mass-assign
}
the 'student_type' are not included, which means they are exempted.
Guarded is the reverse of fillable. If fillable specifies which fields to be mass assigned, guarded specifies which fields are not mass assignable. So in the model:
class Student extends Model {
protected $guarded = ['student_type']; //the field name inside the array is not mass-assignable
}
you should use either $fillable or $guarded - not both.
For more details open link:- Mass Assignment