How to Display Images from Laravel Public Folder in a Vue Component
In this lesson, we are going to see how to display images from Laravel public folder in a Vue component, let's assume that we want to display a user's profile picture from the Laravel public folder.
Update the User model
First, let's update the User model, we append a new attribute to the model which will return the full path of the image using an accessor.
<?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);
}
}
Display the image
Next, to display the image in the Vue component we use the code below:
<img :src="user.image" alt="Profile Image" class="img-fluid rounded">