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.
To create an accessor, create a public function in the model with the following naming conventions:
get
.get
should be followed by the attribute name in Pascal case. For example, to mutate the created_at
attribute, use CreatedAt
.Following these rules to create an accessor for the created_at
attribute.
getCreatedAtAttribute
in the user model.public function getCreatedAtAttribute()
{
return Carbon::parse($this->attributes['created_at'])->diffForHumans();
}
created_at
to the human-readable version of whatever is in the database.{
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"
}