PHP
Customizing Eloquent Attribute Accessors and Mutators
Learn to automatically format model attributes on retrieval and modification using Eloquent accessors and mutators for clean, consistent data handling.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class Product extends Model
{
// Accessor: Automatically capitalize product names when retrieved
public function getNameAttribute($value)
{
return ucfirst($value);
}
// Mutator: Automatically convert product names to lowercase when saved
public function setNameAttribute($value)
{
$this->attributes['name'] = strtolower($value);
}
// Accessor for a derived attribute (not directly a database column)
// This will be accessible as $product->full_name
public function getFullNameAttribute()
{
return "{$this->name} (SKU: {$this->sku})";
}
}
// Usage (assuming a Product model instance)
$product = App\Models\Product::find(1);
// When retrieving, the accessor `getNameAttribute` is automatically called
echo "Retrieved Name: " . $product->name . "
"; // e.g., 'Awesome Widget' -> 'Awesome widget'
// When setting, the mutator `setNameAttribute` is automatically called
$product->name = 'SUPER new PRODUCT';
$product->save(); // 'SUPER new PRODUCT' will be saved as 'super new product'
// Accessing the derived attribute
echo "Full Name: " . $product->full_name . "
";
How it works: This snippet illustrates Eloquent accessors and mutators, powerful tools for transforming model attributes. Accessors (`get{AttributeName}Attribute`) are invoked when an attribute is retrieved, allowing you to format or manipulate data for display (e.g., capitalizing a name). Mutators (`set{AttributeName}Attribute`) are called before an attribute is saved, enabling data sanitization or transformation before storage (e.g., converting to lowercase). It also demonstrates creating derived attributes that don't map directly to database columns.