Laravel Mass Assignment, Guarded or Fillable?

Code With Travel
2 min readDec 2, 2017

Mass assignment is a process of sending an array of data that will be saved to the specified model at once. In general, you don’t need to save data on your model on one by one basis, but rather in a single process.

Mass assignment is good, but there are certain security problems behind it. What if someone passes value to the model and without protection they can definitely modify all fields including the ID. That’s not good.

Let’s say you have ‘students‘ table, with fieldsstudent_type, first_name, last_name, dob, gender”. You may want to mass assign “first_name, last_name, dob, gender” but you want to protect student_type from being directly changed. That’s where fillable and guarded take into place.

What is Fillable?

Fillable lets you specify which fields is mass-assignable in your model. Lets take the above example, you can do it by adding the special variable $fillable to the model. So in the model:

class Student extends Model {protected $fillable = [‘first_name’, ‘last_name’, ‘email’]; //← only the field names inside the array can be mass-assign}

As you have noticed, the ‘id, student_type‘ are not included, which means they are exempted.

What is Guarded?

Guarded is the reverse of fillable. If fillable specifies which fields to be mass assigned, guarded specifies which fields are not mass assignable. So in the model:

class Student extends Model {
protected $guarded = [‘id’, ‘student_type’]; //← the field name inside the array is not mass-assignable
}

If you want to block all fields from being mass-assign you can just do this.

protected $guarded = [‘*’];

So when will you use fillable or guarded?

Using fillable is good when you have 2–10 fields, but what if you have 20–50 fields in your model? I have experienced creating a table with 56 fields to be exact, and just 3 out of those fields are needed to be protected. Trust me, it’s quite of a work. “I’m not saying that it’s not good” using fillable in this situation, you may, but if you want an easier way to secure it from mass-assignment, then guarded will be more preferable.

Last words.

While $fillable serves as a “white list” of attributes that should be mass assignable, you may also choose to use $guarded. The $guarded property should contain an array of attributes that you do not want to be mass assignable. All other attributes not in the array will be mass assignable. So, $guarded functions like a “black list”. Of course, you should use either $fillable or $guarded — not both.

--

--