← Back to all snippets
PHP

Using Eloquent Accessors and Mutators for Data Transformation

Transform model attributes automatically when retrieving or setting them using Laravel Eloquent accessors and mutators, perfect for formatting or encryption.

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Get the user's first name.
     * For Laravel 9+ using new Attribute casting.
     */
    protected function firstName(): Attribute
    {
        return Attribute::make(
            get: fn (string $value) => ucfirst($value),
            set: fn (string $value) => strtolower($value),
        );
    }

    /**
     * Old style accessor for Laravel < 9.
     * public function getFullNameAttribute()
     * {
     *     return "{$this->first_name} {$this->last_name}";
     * }
     */
}
How it works: This snippet demonstrates how to use Eloquent Accessors and Mutators for automatic data transformation. Using the new `Attribute::make()` syntax (Laravel 9+), the `get` closure defines an accessor that capitalizes the first letter of the `first_name` attribute whenever it's retrieved. The `set` closure defines a mutator that converts the `first_name` to lowercase before it's saved to the database. This allows for consistent data formatting directly within 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