PHP

Secure Mass Assignment in Laravel Eloquent

Learn how to protect your Laravel Eloquent models from unwanted mass assignment vulnerabilities by defining fillable or guarded attributes, enhancing application security.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    // Option 1: Define allowed attributes (preferred for security)
    protected $fillable = [
        'title',
        'content',
        'user_id',
    ];

    // Option 2: Define forbidden attributes (less secure but useful for specific cases)
    // protected $guarded = ['id', 'created_at', 'updated_at'];

    // To allow all mass assignment (use with extreme caution)
    // protected $guarded = [];
}

// Example usage:
// $post = App\Models\Post::create([
//     'title' => 'My New Post',
//     'content' => 'This is the content.',
//     'user_id' => 1,
// ]);

// This will throw a MassAssignmentException if 'is_admin' is not fillable or is guarded
// $user = App\Models\User::create(['name' => 'Alice', 'email' => '[email protected]', 'is_admin' => true]);
How it works: Mass assignment is a common vulnerability where a user can pass unexpected HTTP parameters to change attributes that are not intended to be changed. Laravel Eloquent protects against this by default. You can define `protected $fillable` to specify which attributes *can* be mass-assigned, or `protected $guarded` to specify which attributes *cannot* be mass-assigned. It's generally safer to use `$fillable` as it whitelists attributes.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs