How to Use Accessor in Eloquent: Simple Guide
In Laravel Eloquent, you create an accessor by defining a
get{AttributeName}Attribute method in your model. This method lets you customize how a model attribute is retrieved, allowing you to modify or format the value before it is returned.Syntax
An accessor method in an Eloquent model follows this pattern:
get: prefix indicating it is an accessor{AttributeName}: the attribute name in StudlyCaseAttribute: suffix required by Laravel- The method returns the modified or computed value for the attribute
php
public function get{AttributeName}Attribute($value) { // modify or format $value return $modifiedValue; }
Example
This example shows how to create an accessor to always return a user's name in uppercase when accessing the name attribute.
php
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class User extends Model { // Accessor for 'name' attribute public function getNameAttribute($value) { return strtoupper($value); } } // Usage example $user = new User(); $user->name = 'john doe'; echo $user->name; // Outputs: JOHN DOE
Output
JOHN DOE
Common Pitfalls
- Not using the correct method name format: it must start with
get, end withAttribute, and have the attribute name in StudlyCase in the middle. - For attributes that do not exist in the database, you can create accessors but must ensure the attribute is set or computed.
- Accessors only modify how attributes are retrieved, not how they are saved. Use mutators for saving modifications.
php
<?php // Wrong accessor name - will not work public function name() { return strtoupper($this->attributes['name']); } // Correct accessor name public function getNameAttribute($value) { return strtoupper($value); }
Quick Reference
| Concept | Description |
|---|---|
| Accessor Method Name | get{AttributeName}Attribute |
| Parameter | Original attribute value from database |
| Return | Modified or computed attribute value |
| Purpose | Customize how attribute values are retrieved |
| Use Case | Format, combine, or compute attribute values on access |
Key Takeaways
Define an accessor by creating a method named get{AttributeName}Attribute in your Eloquent model.
Accessors let you change how attribute values are returned without changing the database.
Always use StudlyCase for the attribute name in the accessor method.
Accessors only affect reading attributes; use mutators to modify values before saving.
Common mistakes include wrong method names and misunderstanding accessor purpose.