Accessor and mutator in laravel 9

Accessor and mutator in laravel 9

02-Sep-2022
| |
Image Carousel

Table of Content   

  1.  Open a model
  2.  

Accessor and Mutator allow you to get and set attribute with eloquesnt , like in accessor it simply add some values to a particular column whenever you retrieve the data from database using eloquent..

 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 9 , mutator in laravel 9 , add base url in image using laravel , how to accessor in laravel 9,laravel , php ,laravel-php , mvc laravel, advance laravel , bugs in laravel , laravel advance level,
Related Articles
Load More

Newsletter