PHP

Securing Eloquent Models with Mass Assignment Protection

Learn how to protect your Laravel Eloquent models from unwanted mass assignment vulnerabilities using the `$fillable` or `$guarded` properties for secure data handling.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'title',
        'content',
        'user_id',
    ];

    /**
     * The attributes that aren't mass assignable.
     *
     * @var array<int, string>
     */
    // protected $guarded = [
    //     'is_admin'
    // ];

    // Example usage in a controller
    // Post::create(['title' => 'My New Post', 'content' => 'Post body.', 'user_id' => 1]);
    // This will work because 'title', 'content', 'user_id' are in $fillable.

    // If 'is_admin' was in $guarded, you could not mass assign it.
    // Post::create(['title' => 'Test', 'content' => '...', 'is_admin' => true]); // 'is_admin' would be ignored if guarded
}
How it works: Eloquent's mass assignment protection prevents malicious users from updating unintended database columns when passing an array of data to `create`, `update`, or `fill` methods. You can define `$fillable` to specify which attributes *can* be mass assigned, or `$guarded` to specify which attributes *cannot* be mass assigned. Using `$fillable` is generally preferred for security, as it whitelists accepted attributes, ensuring only explicitly allowed data is written to the database.

Need help integrating this into your project?

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

Hire DigitalCodeLabs