PHP
Laravel Eloquent Mass Assignment Protection (fillable/guarded)
Secure your Laravel application by understanding Eloquent's mass assignment protection. Learn to use `$fillable` or `$guarded` properties to control which model attributes can be mass-assigned.
// In your App\Models\User.php or any other model
// Option 1: Using $fillable (whitelist)
// Only 'name', 'email', 'password' can be mass assigned
protected $fillable = [
'name',
'email',
'password',
];
// Option 2: Using $guarded (blacklist)
// All attributes CAN be mass assigned EXCEPT 'is_admin'
// If you have a few restricted fields, this might be simpler
protected $guarded = [
'is_admin',
];
// To allow all mass assignment (not recommended for security)
// protected $guarded = [];
// Example of mass assignment
$user = App\Models\User::create([
'name' => 'John Doe',
'email' => '[email protected]',
'password' => 'secret',
'is_admin' => true, // Will be ignored if 'is_admin' is in $guarded
]);
How it works: Eloquent's mass assignment protection prevents unauthorized attribute updates. You can define a `$fillable` array to whitelist attributes that are allowed for mass assignment (e.g., `User::create([...])`), or use a `$guarded` array to blacklist attributes that should never be mass-assigned. Using `$fillable` is generally preferred for stronger security as it requires explicit permission for each attribute.