Courses

Laravel 11 Eloquent: Expert Level

Attributes: Accessors and Mutators

Summary of this lesson:
- Implementing Eloquent Accessors and Mutators
- Working with attribute transformations
- Understanding new vs old syntax
- Handling date formatting with attributes

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 28 lessons of this course? (71 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord