0
0
LaravelHow-ToBeginner · 3 min read

How to Define Guarded in Eloquent Models in Laravel

In Laravel Eloquent, you define guarded as a protected array property in your model to specify which attributes should NOT be mass assignable. This helps protect sensitive fields from being overwritten during mass assignment operations like create() or update().
📐

Syntax

The guarded property is a protected array in an Eloquent model that lists attributes you want to protect from mass assignment. It looks like this:

  • protected $guarded = ['field1', 'field2']; means these fields cannot be mass assigned.
  • If you set protected $guarded = [];, it means no fields are guarded and all are mass assignable.
php
class User extends Model {
    protected $guarded = ['id', 'password'];
}
💻

Example

This example shows a User model where id and password are guarded. When creating a user with mass assignment, these fields cannot be set directly.

php
<?php
use Illuminate\Database\Eloquent\Model;

class User extends Model {
    protected $guarded = ['id', 'password'];
}

// Usage example
$user = User::create([
    'name' => 'Alice',
    'email' => 'alice@example.com',
    'password' => 'secret', // This will be ignored because it's guarded
]);

// The password attribute will NOT be set by mass assignment
// You must set it manually if needed
$user->password = bcrypt('secret');
$user->save();

// Output the user attributes
return $user->toArray();
Output
{"name":"Alice","email":"alice@example.com"}
⚠️

Common Pitfalls

Common mistakes when using guarded include:

  • Setting protected $guarded = ['*']; which blocks all mass assignment and can cause unexpected failures.
  • Forgetting to guard sensitive fields like id or password, which can lead to security issues.
  • Using both fillable and guarded properties at the same time, which can cause confusion. It's best to use one approach consistently.
php
class Product extends Model {
    // Wrong: guarding all fields disables mass assignment
    protected $guarded = ['*'];
}

class ProductCorrect extends Model {
    // Right: guard only sensitive fields
    protected $guarded = ['id'];
}
📊

Quick Reference

PropertyDescriptionExample
$guardedArray of attributes NOT mass assignableprotected $guarded = ['id', 'password'];
Empty $guardedNo attributes are guarded, all mass assignableprotected $guarded = [];
$guarded = ['*']All attributes guarded, disables mass assignmentprotected $guarded = ['*'];

Key Takeaways

Use protected $guarded in your Eloquent model to protect attributes from mass assignment.
Setting $guarded = [] allows all attributes to be mass assigned safely.
Avoid setting $guarded = ['*'] unless you want to disable mass assignment completely.
Do not mix fillable and guarded properties to prevent confusion.
Always guard sensitive fields like id and password to improve security.