PHP

Defining Custom Accessors and Mutators in Eloquent

Learn how to format and modify Eloquent model attributes automatically using Laravel's modern Attribute definition.

use Illuminate\Database\Eloquent\Casts\Attribute;

protected function fullName(): Attribute
{
    return Attribute::make(
        get: fn ($value, $attributes) => $attributes['first_name'] . ' ' . $attributes['last_name'],
    );
}
How it works: This snippet shows how to define a custom accessor using the modern Attribute class in Laravel. It computes a virtual 'full_name' attribute combining 'first_name' and 'last_name' whenever the property is accessed on the model.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs