Laravel Accessors Explained: Format and Compute Model Attributes

In Laravel, accessors offer a clean and powerful way to define how model attributes should be formatted or mutated when accessed. This feature is particularly useful when you need to manipulate model data before it’s returned — for example, to format dates, append full names, or convert values into human-readable forms.
In this article, we'll explore what accessors are, why they're useful, and how to use them effectively in your Laravel applications.
🔍 What Are Accessors?
An accessor is a method that Laravel automatically calls when you retrieve an attribute on a model. It allows you to transform or manipulate that attribute’s value before it’s returned.
Syntax:
To define an accessor, you create a method using this naming convention:t
get{StudlyCaseAttributeName}Attribute
For example, if your attribute is full_name, the method would be:
public function getFullNameAttribute()
{ return $this->first_name . ' ' . $this->last_name; }
When you access $user->full_name, Laravel will automatically call this method.
✅ When to Use Accessors
Accessors are ideal for:
- Concatenating fields (e.g., full name)
- Formatting dates or numbers
- Converting enums or booleans to readable text
- Creating computed properties
- Appending attributes to JSON responses
💡 Example: Creating a Full Name Accessor
Imagine a User model with first_name and last_name columns:
php CopyEdit class User extends Model { public function getFullNameAttribute() { return ucfirst($this->first_name) . ' ' . ucfirst($this->last_name); } }
Usage:
php CopyEdit $user = User::find(1); echo $user->full_name; // Outputs: John Doe
Even though full_name is not a column in the database, it behaves like a normal attribute.
🗂️ Appending Accessors to JSON Responses
By default, computed attributes (like accessors) won’t be included when you serialize models to JSON or arrays — unless you explicitly tell Laravel.
Option 1: Use $appends in the model:
protected $appends = ['full_name'];
Now full_name will appear in:
return response()->json($user);
Option 2: Use makeHidden() or makeVisible():
$user->makeVisible('full_name');
🧠 Example: Boolean to Readable Text
CopyEdit
class User extends Model { public function getIsActiveTextAttribute() { return $this->is_active ? 'Active' : 'Inactive'; } } echo $user->is_active_text; // "Active" or "Inactive"
⏳ Example: Formatting Dates
php CopyEdit public function getFormattedCreatedAtAttribute() { return $this->created_at->format('d M, Y'); }
Usage:
echo $user->formatted_created_at; // "01 Jul, 2025"
⚙️ Accessors in Laravel 9+ (Using Attribute class)
From Laravel 9 onward, you can define accessors using the fluent Attribute class, which improves clarity and testability.
use Illuminate\Database\Eloquent\Casts\Attribute;
class User extends Model { protected function fullName(): Attribute { return Attribute::make( get: fn () => ucfirst($this->first_name) . ' ' . ucfirst($this->last_name), ); } }
This modern approach is recommended for Laravel 9 and above.
📌 Tips for Using Accessors
- Avoid heavy logic inside accessors — keep them lightweight.
- Cache complex results if reused often.
- Use Laravel’s mutators alongside accessors to set custom values.
- Use accessors with API Resources to present data cleanly.
🔁 Accessors vs Mutators
FeatureAccessorsMutatorsPurposeFormat value when getting an attributeFormat value when setting an attributeNamingget{Attribute}Attributeset{Attribute}AttributeUse CaseFormat date, full name, readable statusEncrypt password, lowercase email
🚀 Conclusion
Accessors are a hidden gem in Laravel that help you cleanly manage how data is presented from your models. Whether you're building APIs or web apps, accessors simplify formatting, reduce clutter in your controllers/views, and improve code maintainability.
Start using accessors today to make your Laravel models smarter and cleaner!
Comments (0)