The danger of using request()->all(). and how to protect it

one of the common mistakes between laravel developers including me, that they are like using request()->all();
Model::create($request->all()); // create a new record with all comming data
that because it’s much shorter than define each column you need to store in the database, but it might make a security issue in your application.
For example: if you have a priority fillable field that only available for the administrators, so the attacker can guess the name of this field and pass it to the request through a hidden field inside the form, even if he doesn’t have any permission to do it.
so if you like to use $request->all(); you should be very careful about these priority fields.
But now, how can I protect it?
there are several ways to protect yourself from this kind of attack.
1- Use guarded property in your eloquent model
add a new property protected $guarded to your eloquent model to refuse the priority fields to be filled and only accept the other fields in the fillable property.
for example:
but wait a minute, there’s a little problem with this.
imagine you have another form in the admin panel that must give admins the ability to update guarded fields.
well, there are two ways to solve this.
- create a new instance of your model, set this attribute value, and then call the save() method instead of using create() method.
- use forceCreate instead of create method to avoid mass assignment:
you can use the same ways while updating
2- use only(), except() methods:
you can use only() method that tells the eloquent to accept some attributes and avoid the rest of them.
but what if you have tens of attributes, it will be so hard to define each one, and it doesn’t make sense.
in this case, you can use the opposite of only() method calls except().
the except() method accepts an array with the attributes you want to avoid, and it will accept the rest of the request attributes.
3- use laravel form request
you can use form request to validate your request and only insert the validated attributes using validated() method.
this will create a new user with the only fields you validated and avoid any other passed attributes.
And that’s it! Now you know how to protect your priority fields with some solutions, I always accept any advice, so if you find anything important or you have any additions to the same topic, please let me know!