PHP
Secure Mass Assignment with Eloquent $fillable
Prevent unintended database updates by explicitly defining fillable attributes in your Laravel Eloquent models, enhancing application security and data integrity.
<?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',
'published_at',
];
// Alternatively, to protect certain fields and allow all others:
// protected $guarded = ['id', 'created_at', 'updated_at'];
}
// Usage example:
$post = Post::create([
'title' => 'My New Post',
'content' => 'This is the content of my new post.',
'user_id' => 1,
'published_at' => now(),
'is_admin_post' => true // This attribute would be ignored if not in $fillable
]);
How it works: This snippet demonstrates how to use the `$fillable` property in a Laravel Eloquent model. By specifying an array of attribute names, you are whitelisting which columns can be mass-assigned using methods like `create()`, `fill()`, or `update()`. This is a critical security feature that prevents users from injecting unwanted data into columns, such as 'is_admin' flags. Alternatively, you can use `$guarded` to specify attributes that should *not* be mass-assignable, allowing all others. If neither `$fillable` nor `$guarded` are set, mass assignment is disabled by default for all attributes.