HomeLARAVELExplain fillable vs guarded.

Explain fillable vs guarded.

In Laravel Eloquent models, when you perform mass assignment (for example using Model::create($request->all()) or update($data)), Laravel needs to know which attributes are safe to be written into the database.

That’s where $fillable and $guarded come in.


🔹 $fillable

  • It is a whitelist of attributes that you allow for mass assignment.
  • Only the fields listed inside $fillable can be filled using create() or update().

✅ Example:

class User extends Model
{
    protected $fillable = ['name', 'email', 'password'];
}

Now:

User::create([
    'name' => 'Himanshu',
    'email' => 'himanshu@example.com',
    'password' => bcrypt('secret'),
    'is_admin' => true   // ❌ ignored (not in fillable)
]);

Here, is_admin won’t be saved because it is not in $fillable.


🔹 $guarded

  • It is the opposite of $fillable.
  • It is a blacklist of attributes that you want to protect from mass assignment.
  • All other attributes (except those listed in $guarded) are mass assignable.

✅ Example:

class User extends Model
{
    protected $guarded = ['is_admin'];
}

Now:

User::create([
    'name' => 'Himanshu',
    'email' => 'himanshu@example.com',
    'password' => bcrypt('secret'),
    'is_admin' => true   // ❌ ignored (guarded)
]);

Here, is_admin won’t be saved because it is guarded.


🔹 Key Difference

  • $fillable → Only listed fields are mass assignable (strict control).
  • $guarded → All fields are mass assignable except those listed (loose control).

👉 You typically use one or the other, not both.


🔹 Special Case

If you want to allow all attributes:

protected $guarded = [];

If you want to block all attributes (not recommended):

protected $fillable = [];

Rule of Thumb:

  • Use $fillable when you want to specify exactly which fields are safe (more secure, common practice).
  • Use $guarded when most fields are safe, and you just want to block a few sensitive ones.

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *