DEV Community

Cover image for   A Brief Overview of Mass Assignment in Laravel
CALVIN JOB PURAM
CALVIN JOB PURAM

Posted on

A Brief Overview of Mass Assignment in Laravel

Laravel's ORM (Eloquent) provides an extremely easy way to communicate with a database. Each database table has a model class which is used to interact with a table. Most object-relational mappers (ORM) have the ability to mass-assign properties directly into the database, which is a security vulnerability.

What then is mass assignment? simply it is a process of sending an array of data that will be saved to a specified model at once. Usually, you don't need to save data one by one you can do that in a single process. Mass assignment is something most programmers make use of as it provides a convenient way to populate the properties of a model object from a form. Unfortunately, it's simplicity can make it a target for hackers. What if someone passes a value to the model and without protection they can directly modify all fields including the ID which is not good.

Let's say we have an 'employee' table which has fields 'first_name, last_name, employee_type' you may want to mass assign 'first_name, last_name' but you may want to protect 'employee_type' from being directly changed. this is where we need fillable and guarded.

What Then is Fillable

Fillable specifies the fields that can be mass assign in your model and this can be achieved by adding a property $fillable in your model as shown below

<?php
class Employee extends Model {

  protected $fillable = ['first_name', 'last_name'];

  //only the fields inside this array can be mass-assign
}
Enter fullscreen mode Exit fullscreen mode

the 'employee_type' is exempted because we don't want to mass assign it.

What Then is Guarded

Guarded is the reverse of fillable which specifies the fields that are not mass assignable. we specify such using a property $guarded in our model class

<?php
class Employee extends Model {

  protected $guarded = ['employee_id'];

  //only the field name inside this array cannot be mass-assignable
}
Enter fullscreen mode Exit fullscreen mode

if you want to block all fields from being mass-assign, you can add '*' in your guarded array ad shown below

<?php
class Employee extends Model {

  protected $guarded = ['*'];

}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)