🔧 Syntax: Defining an Accessor

✅ Laravel 9+ and 10 (Using Attribute class):

  use Illuminate\Database\Eloquent\Casts\Attribute;

class User extends Model
{
    protected function name(): Attribute
    {
        return Attribute::make(
            get: fn ($value) => ucfirst($value),
        );
    }
}

Here, whenever you access $user->name, Laravel will run the accessor function.


🧾 Laravel < 9 (Legacy Accessor Syntax)

 public function getNameAttribute($value)
{
    return ucfirst($value);
}

The method must follow this naming pattern:

get{StudlyCaseColumnName}Attribute

Example: For a column email_verified_at, the method should be:

 public function getEmailVerifiedAtAttribute($value)

✅ Practical Use Cases for Accessors

1. Capitalizing a Name

 protected function name(): Attribute
{
    return Attribute::make(
        get: fn ($value) => ucwords($value),
    );
}

2. Formatting Dates

protected function createdAt(): Attribute
{
    return Attribute::make(
        get: fn ($value) => \Carbon\Carbon::parse($value)->format('d M, Y'),
    );
}

3. Full Name from first_name and last_name

public function getFullNameAttribute()
{
    return $this->first_name . ' ' . $this->last_name;
}

Usage:

$user->full_name;

No such column exists, but the accessor makes it feel like it does.


📌 Accessors with Casting

Accessors can work alongside casts, but they run after any casts defined in $casts.

Example:

protected $casts = [
    'created_at' => 'datetime',
];

Then your accessor will get a Carbon instance automatically:

protected function createdAt(): Attribute
{
    return Attribute::make(
        get: fn ($date) => $date->format('Y-m-d H:i'),
    );
}

⚠️ Important Notes

  • Accessors don’t change the actual database values.
  • They only modify the output when you retrieve attributes.
  • Don’t use accessors for database logic or things that require querying.
  • Laravel caches accessors per request, so performance is not an issue for basic usage.

📚 Accessors + API Responses

If you're building an API using Eloquent Resources or returning models as JSON:

  • Accessor values will be included automatically in toArray() or toJson() if the property is accessed.

You can also include them with:

protected $appends = ['full_name'];

Then it becomes part of the API response.


🧪 Example Model

class User extends Model
{
    protected function name(): Attribute
    {
        return Attribute::make(
            get: fn ($value) => ucwords($value),
        );
    }

    public function getFullNameAttribute()
    {
        return "{$this->first_name} {$this->last_name}";
    }

    protected $appends = ['full_name'];
}

🏁 Summary

ConceptDescriptionWhat it isA method to transform model attributes when accessedDoes it store?❌ No, it doesn’t change the DB valueWhen used?Automatically when accessing the property (e.g., $user->name)Syntax (Laravel 9+)protected function column(): Attribute { return Attribute::make(...); }Legacy syntaxpublic function getColumnAttribute($value)Works with API?✅ Yes, include via $appends or access it in JSON responses