Pusher real-time Notification with Laravel and React.js
Read More
When working with Laravel Eloquent models, accessors are a powerful way to create custom attributes dynamically. Whether you're formatting user names, generating file paths, or combining multiple fields, accessors let you add flexibility without changing your database structure.
In this guide, we’ll explore how to define, use, and optimize accessors in Laravel — including when to use (and not use) the $appends
property.
An accessor is a custom attribute you define on your model using a naming convention: get{StudlyCaseAttributeName}Attribute
.
public function getFullNameAttribute()
{
return $this->first_name . ' ' . $this->last_name;
}
You can now access this like a real attribute:
$user = User::first();
echo $user->full_name; // John Doe
Accessors are useful for:
Combining multiple fields (e.g., full name)
Formatting values (e.g., dates, slugs, prices)
Returning fallback/default values (e.g., image paths)
Generating virtual fields for APIs
Let’s say each company has a logo. If the logo is missing, you want to return a default image.
Recent posts form our Blog
0 Comments
Like 1