|1||What are accessor and mutator|
|2||get and set attributes|
|3||Calling accessor and mutator|
Accessor and Mutator allow you to get and set attribute with eloquent , like in accessor it simply add some values to a particular column whenever you retrieve the data from database using eloquent for eg - you want to get all the names of the users in capital letters or we want the image along with the url of public folder all the things has been done by using accessor , it will convert name of the user ( 'developer-corner' => 'DEVELOPER-CORNER' ) and image as ( 'user.jpg' => 'http://127.0.0.1:8000/public/images/user.jpg' ) and in mutator it set the attribute while saving into the database for eg - when we are saving the form in database and some of the fields like name we want in small alphabets the we use mutator ( 'Developer-Corner' => 'developer-corner' ) .
get and set attributes are two inbuilt laravel attributes to use feature of accessor and mutator , where get belongs to accessor and set belongs to mutators as the name describes itself get means when you are getting values from database and set means when you are saving the values into the database.
in App/Models/User.php Copy
Also read:HOW TO CREATE COMPONENTS IN LARAVEL 9
First we have to include the attribute class by using ( use ) as show ( protected function Name(): Attribute ) this function is called by column name from database like i have users table and my column name is name and very
important ( First letter of your column name which you are used as function must be capital like my column names are name and image so i used Name and Image) ..
Secondly i choose protected function Image(): Attribute , whenever you are using API in laravel you always initialise base url in controller but you can add this function in model simply and call it..And don't need to change for localhost or on Live Serrve.
In any Controller Copy
Also read :HELPER OR COMMON FUNCTION IN LARAVEL 9
The result i get from printing the variables.