PHP

Secure Mass Assignment in Eloquent

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

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'price',
        'description',
    ];

    /**
     * The attributes that aren't mass assignable.
     *
     * @var array<int, string>
     */
    protected $guarded = [
        'id',
        // 'created_at', // You could guard these if you wanted manual control
        // 'updated_at',
    ];

    // Example of usage
    public function storeProduct(array $data)
    {
        // This will only fill 'name', 'price', 'description'
        // 'id', 'is_admin' or other non-fillable attributes will be ignored.
        return Product::create($data);
    }
}
How it works: Mass assignment allows passing an array to a model's `create` or `update` method. Without protection, malicious users could inject unwanted data (e.g., change `is_admin` field). `$fillable` specifies a whitelist of attributes that *can* be mass assigned, while `$guarded` specifies a blacklist of attributes that *cannot* be mass assigned. Using `$fillable` is generally recommended for better security and explicit control over assignable attributes.

Need help integrating this into your project?

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

Hire DigitalCodeLabs