← Back to all snippets
PHP

Customizing Eloquent Attribute Formatting with Accessors and Mutators

Enhance Eloquent model attributes by creating custom accessors to format data upon retrieval and mutators to transform data before saving, improving data consistency.

<?php
namespace App\Models;

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

class Product extends Model
{
    /**
     * Get the product's price, formatted as currency.
     */
    protected function price(): Attribute
    {
        return Attribute::make(
            get: fn (string $value) => '$' . number_format((float) $value, 2),
            set: fn (string $value) => (float) str_replace(['$', ','], '', $value),
        );
    }

    /**
     * Get the user's full name.
     */
    protected function fullName(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->first_name . ' ' . $this->last_name,
        );
    }

    // Usage:
    // $product = Product::find(1);
    // echo $product->price; // e.g., $10.50
    // $product->price = '$15.99'; // Saves 15.99 to the database
    //
    // $user = User::find(1);
    // echo $user->full_name;
}
How it works: Accessors and Mutators provide a powerful way to interact with your model's attributes. An accessor (the `get` closure) transforms an attribute's value when it is retrieved from the model, for example, formatting a price. A mutator (the `set` closure) transforms an attribute's value before it is saved to the database. Starting with Laravel 9, the `Attribute::make()` fluent syntax is recommended for defining these.

Need help integrating this into your project?

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

Hire DigitalCodeLabs