In Laravel's ORM, accessing and manipulating data directly from the database is a common task. However, there are scenarios where you need to transform data before retrieving it form the database or before saving it back. Laravel provides a convenient way to achieve this through Accessors and Mutators.
Understanding Accessors and Mutators
Accessors
Accessors allow you to manipulate attributes' values when retrieving them from a model. They provide a way to define custom attribute getters, allowing you to format or modify data before it's presented to the application.
Naming Convention:
Accessors are named using the get
keyword followed by the studly case attribute name and the Attribute
suffix.
- Example: If you have an attribute named
created_at
, the accessor method should be namedgetCreatedAtAttribute
.
Example:
Consider a scenario where you store dates in your database but want to format them differently when displaying to user. You can create an accessor to achieve this:
// Post.php (Model)
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
class Post extends Model
{
public function getCreatedAtAttribute($value)
{
return Carbon::parse($value)->format('Y-m-d H:i:s');
}
}
It this example, the getCreatedAtAttributes
method automatically gets called when you access the created_at
attribute on Post
model instance. It uses the Carbon library to parse the date and format it as desired.
$user = User::find(1);
$createdAt = $user->created_at; // Accessing the 'created_at' attribute
echo $createdAt; // Output: Formatted date and time (e.g., 2022-01-30 14:25:00)
Mutators
Conversely, Mutators allow you to modify attribute values before saving them to the database. They intercept attribute values before they are set on the model, giving you the opportunity to modify or format data according to your requirements.
Naming Conventions:
Mutators are named using the set
keyword followed by the studly case attribute name and the Attribute
suffix.
set{AttributeName}Attribute
- Example: If you have an attribute named
name
, the mutator method should be namedsetNameAttribute
.
Example:
Let's say you want to store a user's name in uppercase in the database, regardless of how it is provided. You can achieve this using a mutator:
// User.php (Model)
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function setNameAttribute($value)
{
$this->attributes['name'] = strtoupper($value);
}
}
In this case, the setNameAttributes
method is automatically invoked whenever you attempt to set the name
attribute on a User
model instance. It converts the value to uppercase before storing it in the database.
$user = new User();
$user->name = 'john doe'; // Setting the 'name' attribute
$user->save(); // The mutator will capitalize the name before saving
Practical Use Cases:
- Accessors: Useful for formatting dates, concatenating attributes, or performing computations before displaying data to users.
- Mutators: Handy for enforcing rules, sanitizing data, or performing transformations before persisting data to the database.