Accessor and mutator in laravel 10

Accessor and mutator in laravel 10

14-Sep-2024
| |
Image Carousel

Table of Contents   

S.no Contents-topics
1 What are accessor and mutator
2 get and set attributes
3 Calling accessor and mutator

1:What are 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' ) .

2:get and set attributes

Note : in model our function name should be same as the column name in database like if our column name is "image" so our function name should be "Image" protected function Image(): Attribute

 get and set attributes are two inbuilt laravel 10 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 

 <?php
 
namespace App\Models;
 
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Database\Eloquent\Casts\Attribute;
use URL;
 
class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
 
    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];
 
    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];
 
    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
 
    protected function Name(): Attribute
    {
        return Attribute::make(
            get: fn ($value) => 'I am from '.$value,
            set: fn ($value) => strtolower($value),
        );
    }
 
    protected function Image(): Attribute
    {
        return Attribute::make(
            get: fn ($value) => URL::to('public/images/'.$value.'')
        );
    }
 
 
}

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

    public function getUser()
    {
      $user =  User::find(1);
      print_r($user->name); echo"<br>";
      print_r($user->image);
    }

The result i get from printing the variables.

I am from Developer Corner
http://127.0.0.1:8000/public/images/user.jpg

Tags: accesor in laravel 10 , mutator in laravel 10 , add base url in image using laravel , how to accessor in laravel 10,laravel , php ,laravel-php , mvc laravel, advance laravel , bugs in laravel , laravel advance level,
0 Comments (Please let us know your query)
Leave Comment
Leave Comment
Articles from other Categories
Load More

Newsletter