DEV Community

Cover image for Fillable, Guarded in Laravel ! What’s the difference
Kepson Diaz
Kepson Diaz

Posted on

Fillable, Guarded in Laravel ! What’s the difference

In Laravel, both $fillable and $guarded are attributes used in Eloquent models to control the mass assignment of attributes.
Mass assignment in Laravel refers to the ability to set multiple attributes of a model at once using an array of data.

Fillable :

$fillable is an array that specifies which attributes can be mass assigned. These are the attributes that are allowed to be set using the create or update methods.
Any attributes not included in the fillable array will be ignored during mass assignment.

class YourModele extends Model
{
        protected $fillable = [
        'name',
        'email',
        'password',
    ];
}
Enter fullscreen mode Exit fullscreen mode

in this example attributs $name, $email, $password will be mass assigned.

If you wish to allow all attributes of your model to be mass-assigned, you can use the wildcard character * in the $fillable declaration. However, it's essential to understand the security implications of this approach.

class YourModele extends Model
{
    protected $fillable = ['*'];
}
Enter fullscreen mode Exit fullscreen mode

Guarded :

$guarded is also an array but it works in the opposite way. It specifies which attributes are not allowed to be mass assigned. Any attributes not included in the guarded array will be considered safe for mass assignment.

class YourModele extends Model
{
        protected $guarded = [
        'name',
        'email',
        'password',
    ];
}
Enter fullscreen mode Exit fullscreen mode

in this example attributs

$name, $email, $password 
Enter fullscreen mode Exit fullscreen mode

will not be mass assigned.

If you don't want all your model's attributes to be mass assigned, you can use the wildcard * in the $guarded declaration.

class YourModele extends Model
{
    protected $guarded = ['*'];
}
Enter fullscreen mode Exit fullscreen mode

The main difference

The main difference between $fillable and $guarded is the approach they take to define the attributes that can be mass assigned. $fillable explicitly states the allowed attributes, while $guarded explicitly states the disallowed attributes.

why it's important to use $fillable or $guarded

It is important to use either $fillable or $guarded to protect against mass assignment vulnerabilities, which can lead to security risks. By specifying the attributes that can or cannot be mass assigned, you have more control over the data that is being assigned to your models.

Top comments (2)

Collapse
 
mdialloc19 profile image
MdialloC19

This article is clear, concise, and exceptionally well-crafted.

Collapse
 
kepsondiaz profile image
Kepson Diaz

Thanks