I was reading the Eloquent documentation where I came to the the topic of mass assignment of post requests.
So, there are right now two question in my mind which directs to a single point.
1- What are the benefits of mass-assignment?
2- Where we should not use mass-assignment?
The benefits of mass assigment, are mostly to write less code. It is not any faster at execution time...
And it is definitely less secure than a regular old Insert, Update. As it passes user-input blindly into the model.
I avoid using it, and infact have never actually found an appropriate time to actually do so.
Personally I found Mass-assignment very much useful as it not only help you to protect your sensitive fields to get filled without check, like password and ids, but also it help you to assign values to non-sensitive fields quickly.
How Mass-Assign Protects Sensitive Fields: It would not fill/assign values to fields which are not mentioned by you to mass-assign in the protected $fillable property
.
For example you have a User model with fields id, first_name, last_name, email, password.
You can assign values to first_name, last_name, email
as given below:
$user = new User;
$user->first_name = Input::get('first_name');
$user->last_name = Input::get('last_name');
$user->email = Input::get('email');
$user->save();
The above method is acceptable but what if you have more fields? This is where mass-assignment comes to rescue. You can go with the following way:
$user = new User;
$user->fill(Input::all());
$user->save();
But before using the mass-assigning you should make sure that the fields, you want to mass assign are saved in a protected $fillable property of your model as given below other wise you'll get mass assign exception:
protected $fillable = ['first_name', 'last_name', 'email'];
Note: It would be dangerous to include sensitive fields like password
in your protected $fillable
property. Better is you should add your sensitive fields in the protected $guarded
property as given below:
protected $guarded = ['id', 'password'];