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

laravel request
laravel request

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.

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.

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!

Written by

Hello there It’s Muhammed elfeqy from Egypt, a web developer that has a passion in the technical field in general, specialized in web development

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store