When you work with Laravel you may have heard Mass Assignment, Guarded or Fillable. In this article, we will go through each term in detail.
What is Mass Assignment?
Mass assignment is sending an array to model directly for creation, basically setting these bunch of fields rather than setting one by one. See the below example.
$user = new User(Input::all());
Mass assignment is time savvy, but there is a security problem behind it. Suppose if you have an application containing different roles and access. What if someone passes modified values to the model such as user_type or is_admin, they will get full access to the application. So you want to exclude some of the fields from the mass assignment, that’s where the fillable and guarded saves your life.
What is fillable?
Fillable allows you to specify the fields that are mass-assignable into the model. Let’s take this example, you have a table with fields such as id, firstname, lastname, email, user_type. As we said earlier it’s not good to send user_type with mass-assignment. So we write our fillable as below
class User extends Model { protected $fillable = ['firstname', 'lastname', 'email']; //← only the field names inside the array are mass-assignable }
You have noticed, the array is not containing the id and user_type. Which means when we mass-assign these fields are exempted. To update the values you have to explicitly set it on the model and save it.
$user->user_type = 'admin'; $user->save();
Fillable is exactly working as whitelisting the fields.
What is guarded?
We can say guarded is the reverse of fillable. If fillable is specifies which fields to mass-assigned, the guarded specifies which fields are not mass-assignable.
Considering the above table, lets’ write the below code for guarded.
class User extends Model { protected $guarded = ['id', 'user_type']; }
If you want to exclude all fields, use below code.
protected $guarded = ['*'];
When you have more fields in the table, the guarded will be more useful than fillable. Imagine you have a table with 30-50 fields, and you just want to exclude only 5 fields among that. By using fillable you want to specify all 30-40 fields in the array. But with guarded you just need to specify those 5 fields and results in smaller size array.
Hope you have enjoyed the post. Read more details in Laravel Eloquent page
- Just want to thank us? Buy us a Coffee
- May be another day? Shop on Amazon using our links.
Your prices won't change but we get a small commission.
Leave a Reply