PHP
Secure Eloquent Models with Mass Assignment Protection
Implement crucial security measures in Laravel Eloquent by using the `$fillable` or `$guarded` properties to prevent unauthorized mass assignment vulnerabilities when creating or updating models.
// In app/Models/Post.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
// Option 1: Using $fillable (preferred - whitelist of assignable attributes)
protected $fillable = [
'title',
'content',
'user_id',
'is_published',
];
// Option 2: Using $guarded (blacklist of non-assignable attributes)
// protected $guarded = [
// 'id',
// 'created_at',
// 'updated_at',
// ];
// If $guarded is empty, it allows mass assignment for all attributes.
// protected $guarded = []; // DANGER: Allows all attributes to be mass assigned
// Important: You should generally use EITHER $fillable OR $guarded, not both.
}
// Example Usage
// This will work because title and content are in $fillable
$post = App\Models\Post::create([
'title' => 'My New Post',
'content' => 'Lorem ipsum...',
'user_id' => 1,
'is_published' => true,
]);
// This would throw a MassAssignmentException if 'id' was not guarded
// and if you tried to assign it via mass assignment.
// If 'title' wasn't in $fillable, it would also not be assigned.
How it works: Mass assignment is a security vulnerability where users might inject unexpected HTTP request parameters to modify sensitive database columns they shouldn't have access to. Laravel Eloquent protects against this using either the `$fillable` or `$guarded` properties on your models. `$fillable` defines a "whitelist" of attributes that can be mass-assigned, while `$guarded` defines a "blacklist" of attributes that cannot. It is generally recommended to use `$fillable` to explicitly list assignable attributes for better security.