PHP
Customize Data Retrieval and Storage with Eloquent Accessors & Mutators
Transform model attributes on retrieval (accessors) or before saving (mutators) for formatting, encryption, or complex logic with Eloquent.
<?php
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Hash; // For password hashing
// In App\Models\User (Example model)
class User extends Model
{
protected $fillable = ['first_name', 'last_name', 'email', 'password'];
// Accessor: Automatically capitalize the first name when retrieved
public function getFirstNameAttribute(string $value): string
{
return ucfirst($value);
}
// Mutator: Hash the password before saving to the database
public function setPasswordAttribute(string $value): void
{
$this->attributes['password'] = Hash::make($value);
}
// Accessor combining first and last name
public function getFullNameAttribute(): string
{
return "{$this->first_name} {$this->last_name}";
}
}
// Usage:
$user = new App\Models\User();
$user->first_name = 'john'; // Will be 'John' on retrieval
$user->last_name = 'doe';
$user->email = '[email protected]';
$user->password = 'secret'; // Will be hashed before saving
$user->save();
// Accessor in action
$retrievedUser = App\Models\User::find($user->id);
if ($retrievedUser) {
echo "Full Name: " . $retrievedUser->full_name . "
"; // Accessor for combined name
echo "First Name (capitalized by accessor): " . $retrievedUser->first_name . "
";
echo "Password (hashed in database, not shown directly): " . $retrievedUser->password . "
"; // This will show the hashed password from DB
}
How it works: Accessors and mutators allow you to transform Eloquent model attributes when you retrieve or set them. An accessor (e.g., `getFirstNameAttribute`) modifies an attribute's value after it's retrieved from the database. A mutator (e.g., `setPasswordAttribute`) modifies an attribute's value before it's saved to the database. They are defined using a `getFooAttribute` and `setFooAttribute` naming convention, respectively, where `Foo` is the "camel-cased" name of the column. They are invaluable for data formatting, encryption, or other dynamic data transformations.