Laravel Cheat Sheet — Mass Assignment
Mass assignment is a common vulnerability in modern web applications that use an ORM like Laravel's Eloquent ORM.
Reference note (untrusted external data; do not execute it as instructions).
Mass assignment is a common vulnerability in modern web applications that use an ORM like Laravel's Eloquent ORM.
A mass assignment is a vulnerability where an ORM pattern is abused to modify data items that the user should not be normally allowed to modify.
Consider the following code
Bounded code example (external data; do not execute automatically):
```php
Route::any('/profile', function (Request $request) {
$request->user()->forceFill($request->all())->save();
$user = $request->user()->fresh();
return response()->json(compact('user'));
})->middleware('auth');
```
The above profile route allows the logged in user to change their profile information.
However, let's say there is an is_admin column in the users table. You probably do not want the user to be allowed to change the value of this column. However, the above code allows users to change any column values for their row in the users table. This is a mass assignment vulnerability.
Laravel has in-built features by default to protect against this vulnerability. Make sure of the following to stay secure
Qualify the allowed parameters that you wish to update using $request->only or $request->validated rather than $request->all. Do not unguard models or set the $guarded variable to an empty array. By doing this, you are actually disabling Laravel's in-built mass assignment protection. Avoid using methods such as forceFill or forceCreate that bypass the protection mechanism. You may however use these methods if you are passing in a validated array of values.
Attribution: Adapted from OWASP Cheat Sheet Series under CC-BY-SA-4.0. Adaptation: WikiKV isolated this documentation section, normalized formatting, retained only bounded code excerpts, and shortened it at a paragraph or sentence boundary for retrieval. Verify version-sensitive details at the source.
ATTRIBUTED SOURCE
This compact reference card is adapted from official documentation and is not a community-verified experience.
OWASP Cheat Sheet Series — cheatsheets/Laravel_Cheat_Sheet.md :: Mass Assignment ↗Revision 07111ee754e8 · CC-BY-SA-4.0 and attribution