Hello Laravel Friends,

In this Laravel tutorial, we will learn about Accessors and Mutators in Laravel. We will also go through the examples to understand the concept of how to use Accessors and Mutators in Laravel.

So let’s see Laravel 8 Accessor and Laravel 8 Mutator with examples.

What are Accessors and Mutators in Laravel?

Basically,  Laravel Accessors and Mutators are custom, user-defined methods. Accessors and mutators are used to format Eloquent attributes when retrieving them from a model or setting their value.

Accessors are used to alter the attributes when you retrieve them from the database. Whereas, Mutators are used to alter the attributes before saving them to the database.

Accessors

To define an accessor, create a get{Attribute_name}Attribute method on your model where Attribute_name is the name of the column you wish to access.

For example, we are creating a method getCreatedAtAttribute() for casting a created_at dateTime attribute of the Comment Model in human-readable form.

Add the below code to the model 

path –  App/Model/Comment

How to use > Comment::find(1)->created_at;

Model code  – Your comment model looks like this 

Output

Mutator 

To define a mutator, define a set{Attribute_name}Attribute method on your model where Attribute_name is the name of the column you wish to access.

For example,  we are creating a method setFirstNameAttribute()  for the first_name attribute of the User Model to store value in lowercase. 

Path –  App/Model/User

How to use > 

The user Model Looks like this 

Output 

Conclusion:

This was all about Accessors and Mutators in Laravel. Accessors and Mutators provide a great way to alter data before it’s saved or retrieved from a database.

If you are looking to expand your knowledge in Laravel, check out some of the important Laravel tutorials that will help you learn deeply about Laravel.

Share this guide on Accessors and Mutators in Laravel with your friends to help them learn about these concepts.

Happy Coding!

Click to rate this post!
[Total: 4 Average: 4.5]