PHP
Use Eloquent Accessors and Mutators
Transform model attributes on retrieval and storage using Eloquent accessors for formatting and mutators for data manipulation before saving.
// app/Models/User.php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class User extends Model
{
use HasFactory;
protected $fillable = ['first_name', 'last_name', 'email', 'password'];
// Accessor for full_name
public function getFullNameAttribute()
{
return "{$this->first_name} {$this->last_name}";
}
// Mutator for first_name (capitalize)
public function setFirstNameAttribute($value)
{
$this->attributes['first_name'] = Str::title($value);
}
// Mutator for password (hash)
public function setPasswordAttribute($value)
{
$this->attributes['password'] = bcrypt($value);
}
// Example Usage
// $user = User::find(1);
// echo $user->full_name; // Accesses accessor
// $user = new User();
// $user->first_name = 'john'; // Mutator called
// $user->last_name = 'doe';
// $user->password = 'secret'; // Mutator called
// $user->save();
}
How it works: Accessors transform Eloquent attribute values when they are retrieved from the model. They are defined with a `getFooAttribute` method. Mutators transform attribute values before they are saved to the database, defined with a `setFooAttribute` method. This allows for convenient formatting, encryption, or other data manipulations directly within the model.