← Back to all snippets
PHP

Protecting Against Mass Assignment Vulnerabilities in Eloquent

Learn how to prevent mass assignment vulnerabilities in Laravel Eloquent by defining fillable attributes or guarding all attributes in your models.

<?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 = []; // Alternatively, guard nothing to allow all fields
}

// Example usage:
// $post = Post::create([
//     'title' => 'My New Post',
//     'content' => 'Lorem ipsum...', 
//     'user_id' => 1,
//     'is_admin' => true // This field would be ignored if not in $fillable
// ]);
How it works: This snippet demonstrates how to protect your Laravel Eloquent models from mass assignment vulnerabilities. By defining the `$fillable` property, you explicitly list the attributes that are allowed to be mass assigned using methods like `create` or `update`. Alternatively, you can use the `$guarded` property to specify attributes that should *not* be mass assignable, or set `$guarded = []` to allow all attributes to be mass assigned, which is generally discouraged for security reasons.

Need help integrating this into your project?

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

Hire DigitalCodeLabs