PHP
Transforming Model Attributes with Accessors & Mutators
Implement Laravel Eloquent accessors to format or modify attribute values when retrieved, and mutators to transform values before they are saved to the database.
// In app/Models/User.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class User extends Model
{
protected $fillable = ['first_name', 'last_name', 'email'];
/**
* Get the user's full name.
* Accessor
* @return string
*/
public function getFullNameAttribute()
{
return "{$this->first_name} {$this->last_name}";
}
/**
* Set the user's first name.
* Mutator - converts to title case before saving
* @param string $value
* @return void
*/
public function setFirstNameAttribute($value)
{
$this->attributes['first_name'] = Str::title($value);
}
/**
* Set the user's email address.
* Mutator - converts to lowercase before saving
* @param string $value
* @return void
*/
public function setEmailAttribute($value)
{
$this->attributes['email'] = Str::lower($value);
}
}
// Usage example:
$user = new App\Models\User();
$user->first_name = 'john';
$user->last_name = 'DOE';
$user->email = '[email protected]';
$user->save();
$retrievedUser = App\Models\User::find($user->id);
echo "Full Name (Accessor): " . $retrievedUser->full_name . "
";
echo "First Name (Mutator Applied): " . $retrievedUser->first_name . "
";
echo "Email (Mutator Applied): " . $retrievedUser->email . "
";
How it works: Accessors allow you to define custom logic for how an Eloquent attribute is retrieved. For example, `getFullNameAttribute` combines first and last names. Mutators, like `setFirstNameAttribute` and `setEmailAttribute`, allow you to modify an attribute's value before it is saved to the database. This is useful for formatting, sanitization, or encryption, ensuring data consistency.