Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

Attributes: Accessors and Mutators

Premium
5:29

Let's get familiar with a few more terms about Eloquent which are Accessors and Mutators or combined, they are called Attributes from Laravel 9.

If you work with projects before Laravel 9, there may be different syntax in older tutorials or examples. I will show you the old syntax at the end of this lesson.

So, Accessors and Mutators are used if you want to change the value when getting or setting the data. Now, why would you do that?


Example 1: Accessors

For example, you have a created_at field but want to show it in a human format.

Because created_at is automatically casted to a datetime and is a Carbon object, you can use diffForHumans() directly on the field. Now, of course, you can do that in the blade or the API response directly. But what if you want to reuse it in all cases where you use the model, so it makes sense to have some kind of function inside the Model, which is an Accessor.

So, you define the Accessor as an attribute. Interestingly, the Accessor method name is...

The Full Lesson is Only for Premium Members

Want to access all of our courses? (29 h 14 min)

You also get:

54 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

No comments yet…