What are Eloquent accessors in Laravel?
Eloquent accessors are used to determine how some data is processed when it is being retrieved. They come into play when fetching a database resource. For example, you might want to get the created_at attribute as a human-readable time difference every time you get the user. An accessor should be created for the created_at field to do this. This accessor will then do this conversion every time the model is fetched. So in the database, the column is still a DateTime object but will be returned to you as a human-readable time difference.
Creating an accessor
To create an accessor, create a public function in the model with the following naming conventions:
- The name must start with
get. - Then, the
getshould be followed by the attribute name in Pascal case. For example, to mutate thecreated_atattribute, useCreatedAt. - Finally, it should end with attributes.
Code
Following these rules to create an accessor for the created_at attribute.
- Create a public function named
getCreatedAtAttributein the user model.
public function getCreatedAtAttribute()
{
return Carbon::parse($this->attributes['created_at'])->diffForHumans();
}
- Now, this sets the model’s
created_atto the human-readable version of whatever is in the database. - Getting a single user will return something like this:
{
id: 1,
name: "Miss Ruby Wolff I",
email: "jessie.lubowitz@example.net",
username: "white.violette",
slug: "miss-ruby-wolff-i",
email_verified_at: "2021-10-21T14:45:41.000000Z",
created_at: "2 hours ago",
updated_at: "2021-10-21T14:45:41.000000Z"
}