DEV Community

StuartCreed
StuartCreed

Posted on • Updated on

Setting $guarded = [] in Laravel-> Mass Assignment protection

When can I use $guarded = [] in the model?

To quote:
https://laracasts.com/discuss/channels/eloquent/do-i-really-need-to-use-protected-fillable-if

If you are not going to insert values into all fields of a model at once (e.g. $user = new User(request()->all());) as a response to a HTTP request then you can set guarded=[] on the model. Instead you will need to update specific columns only e.g:

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Flight;
use Illuminate\Http\Request;

class FlightController extends Controller
{
    /**
     * Store a new flight in the database.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // Validate the request...

        $flight = new Flight;

        $flight->name = $request->name;

        $flight->save();
    }
}
Enter fullscreen mode Exit fullscreen mode

What is mass assignment?

To quote from:
https://stackoverflow.com/questions/22279435/what-does-mass-assignment-mean-in-laravel

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();

Top comments (0)