How to Define Fillable in Eloquent Models in Laravel
In Laravel Eloquent, define the
fillable property as an array of attributes you want to allow for mass assignment. This protects your model from unwanted data being assigned during operations like create() or update().Syntax
The fillable property is a protected array inside your Eloquent model class. It lists the attributes that can be mass assigned.
- protected $fillable: The property name.
- array of strings: Each string is a column name allowed for mass assignment.
php
class User extends Model { protected $fillable = ['name', 'email', 'password']; }
Example
This example shows a User model with fillable defined. It allows mass assignment only on name, email, and password. When creating a user, only these fields will be saved.
php
<?php use Illuminate\Database\Eloquent\Model; class User extends Model { protected $fillable = ['name', 'email', 'password']; } // Usage example $user = User::create([ 'name' => 'Alice', 'email' => 'alice@example.com', 'password' => bcrypt('secret'), 'is_admin' => true // This will be ignored because it's not fillable ]); // $user->is_admin will be null or default, not true
Output
User record created with name, email, and password only; 'is_admin' ignored.
Common Pitfalls
Common mistakes include:
- Not defining
fillableat all, which blocks all mass assignment by default. - Including sensitive fields like
is_admininfillable, which can lead to security risks. - Confusing
fillablewithguarded.fillableis a whitelist;guardedis a blacklist.
php
<?php // Wrong: allowing sensitive fields class User extends Model { protected $fillable = ['name', 'email', 'password', 'is_admin']; } // Right: exclude sensitive fields class User extends Model { protected $fillable = ['name', 'email', 'password']; }
Quick Reference
| Property | Description | Example |
|---|---|---|
| $fillable | Array of attributes allowed for mass assignment | protected $fillable = ['name', 'email']; |
| $guarded | Array of attributes NOT allowed for mass assignment | protected $guarded = ['is_admin']; |
| Mass Assignment | Assigning multiple attributes at once via create() or update() | User::create(['name' => 'Bob', 'email' => 'bob@example.com']); |
Key Takeaways
Always define the $fillable array in your Eloquent models to allow safe mass assignment.
Include only the attributes you want users to set via mass assignment in $fillable.
Never put sensitive or protected fields like 'is_admin' in $fillable to avoid security risks.
If you don't define $fillable, mass assignment will be blocked by default.
Use $guarded as an alternative to $fillable, but prefer $fillable for clarity.