Mass assignment protection helps keep your app safe by controlling which data can be saved all at once. It stops unwanted or harmful data from being added to your database.
0
0
Mass assignment protection in Laravel
Introduction
When saving user input from forms to the database
When creating or updating records with many fields at once
When you want to prevent users from changing sensitive fields like user roles
When working with APIs that accept bulk data
When you want to avoid accidental data overwrites
Syntax
Laravel
class User extends Model { protected $fillable = ['name', 'email', 'password']; // or protected $guarded = ['is_admin']; }
$fillable lists fields allowed for mass assignment.
$guarded lists fields NOT allowed for mass assignment.
Examples
Only
title and content can be mass assigned.Laravel
class Post extends Model { protected $fillable = ['title', 'content']; }
All fields except
price can be mass assigned.Laravel
class Product extends Model { protected $guarded = ['price']; }
If
is_admin is guarded, it will NOT be set by mass assignment.Laravel
User::create(['name' => 'Anna', 'email' => 'anna@example.com', 'is_admin' => true]);
Sample Program
This example shows a User model with name and email allowed for mass assignment. The is_admin field is not fillable, so it will be ignored when creating the user.
Laravel
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class User extends Model { protected $fillable = ['name', 'email']; } // In a controller or tinker $userData = ['name' => 'John', 'email' => 'john@example.com', 'is_admin' => true]; $user = User::create($userData); // Output user attributes print_r($user->toArray());
OutputSuccess
Important Notes
Always use either $fillable or $guarded to protect your models.
Setting $guarded = [] means all fields are mass assignable (not recommended).
Mass assignment protection helps prevent security issues like users changing admin status.
Summary
Mass assignment protection controls which fields can be set in bulk.
Use $fillable to allow specific fields or $guarded to block specific fields.
This keeps your app safe from unwanted data changes.