PHP

Preventing Mass Assignment Vulnerabilities with Eloquent's fillable and guarded

Learn to secure your Laravel Eloquent models from mass assignment vulnerabilities by defining fillable (allowed attributes) or guarded (protected attributes), ensuring data integrity and application security.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that aren't mass assignable.
     * Use $guarded = [] for no mass assignment protection (use with caution).
     *
     * @var array<int, string>
     */
    protected $guarded = [
        // 'is_admin', // Example of a guarded attribute
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];
}

// Example usage
// $user = User::create([
//     'name' => $request->name,
//     'email' => $request->email,
//     'password' => bcrypt($request->password),
// ]);
How it works: Mass assignment occurs when a user passes an unexpected HTTP parameter and that parameter changes a column in your database you did not expect. Laravel's Eloquent models provide `$fillable` and `$guarded` properties to protect against this. `$fillable` specifies a whitelist of attributes that can be mass assigned, while `$guarded` specifies a blacklist. It's generally recommended to use `$fillable` for better security by explicitly allowing only specific attributes.

Need help integrating this into your project?

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

Hire DigitalCodeLabs