PHP
Secure Mass Assignment with Eloquent Fillable & Guarded
Protect your Laravel Eloquent models from mass assignment vulnerabilities by explicitly defining which attributes are allowed to be mass-assigned using $fillable or $guarded.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'title',
'content',
'user_id',
];
/**
* The attributes that aren't mass assignable.
*
* @var array
*/
// protected $guarded = [
// 'is_admin'
// ];
// Or to allow all mass assignment (use with caution!)
// protected $guarded = [];
}
How it works: Mass assignment occurs when a user passes an array of input values to a model's constructor or `create()` method, and these values are mapped directly to model attributes. Without protection, malicious users could modify sensitive attributes. Eloquent's `$fillable` property defines a whitelist of attributes that can be mass-assigned, while `$guarded` defines a blacklist. It's generally safer to use `$fillable` to explicitly allow only safe attributes.