How to Append a New Attribute to Laravel Eloquent Model
In today's lesson, we are going to see how to append a new attribute to the Laravel eloquent model, let's assume that we have a users table and each user has a "photo_url" field and we want to append an attribute "image" to the User model which will return the full path to the profile image.
Update the User model
First, let's update the user model, we append the attribute "image" and we use the accessor to get the full path of the image.
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
'photo_url'
];
protected $appends = ['image'];
/**
* 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',
];
public function getImageAttribute() {
return asset('storage/'.$this->photo_url);
}
}
How to use
You can use the new appended attribute like the code below:
//vue js
<img :src="user.image" alt="Profile Image" class="img-fluid rounded">
//laravel
<img src="{{user->image}}" alt="Profile Image" class="img-fluid rounded">