PHP
Implementing Mass Assignment Protection with $fillable
Protect your Laravel models from unwanted mass assignment vulnerabilities using the `$fillable` property, ensuring only specified attributes can be set.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'description',
'price',
'category_id',
];
// Example of creating a new product
public static function createProduct(array $data)
{
return self::create($data);
}
// Example of updating an existing product
public static function updateProduct(Product $product, array $data)
{
$product->update($data);
return $product;
}
}
// Usage example in a controller or service:
/*
$productData = [
'name' => 'New Gadget',
'description' => 'A cool new gadget.',
'price' => 99.99,
'category_id' => 1,
'is_admin' => true // This will be ignored if not in $fillable
];
$newProduct = \App\Models\Product::createProduct($productData);
*/
How it works: The `$fillable` property in a Laravel Eloquent model specifies which attributes can be mass assigned. When using methods like `create()` or `update()` with an array of data, only attributes listed in `$fillable` will be set on the model. This is a crucial security feature that prevents malicious users from injecting unexpected data into your database, safeguarding your application from mass assignment vulnerabilities.