In this Blog, we'll understand mutators and accessors of the Eloquent ORM in the Laravel framework by examples.
Laravel, Accessors, and Mutators allow us to alter data while saving and fetching. As per the name, Accessor alters data while accessing and Mutators modify data while saving. The major difference between an accessor and Mutator is that data modification in an accessor is temporary while in a mutator modify data is stored in the database.
For example, if we want to store a user name in upper case in our database then we can define a mutator for that so that when we save the model it will automatically convert the name into uppercase and also store the name in uppercase.
Suppose we store the user's name as first name and last name. We want to display full user names across various pages then we need to add them manually Right!!! But by using accessors we can create an attribute that merges it and use that attribute whenever required.
Create Accessors and Mutators in a Laravel Model
Let's take a practical example. Here, we will create Post Model and define Accessor and Mutator on it.
To create a model, enter the below command into your terminal:
It will create a Model and migration file for Post. Let's modify them one by one:
Here, we have created a basic database structure for our posts table now it's time to migrate it. Enter below command to migrate :
Let's define a Mutator and accessor for the title attribute. The Mutator will be automatically called when we attempt to set the value of the title attribute on the model and Accessor will convert title into title case while fetching data.
Syntax :
Let's modify our model to set Accessor and Mutator for title attribute. So make below changes into Post Model :
Checking Accessor and Mutator
Let's check whether our Accessor and Mutator functions are working or not. Let's use a controller to check it.
let's define the route too.
Testing our Functionality
Now we are ready to test our functionality. open the terminal and run below command :
Open this URL in a browser and it will show location information.
When you open check-accessor then it will find first record and display it. While check-mutator method will create new records from controller values.