How can I properly display an image from Laravel's public folder using React

686 Views Asked by At

I've tried using the asset() function below, but it returns the current path and localhost, when I only want the localhost where the image is located

const assetUrl = import.meta.env.VITE_HOST;

function asset(path) {
    const assetUrl = import.meta.env.VITE_HOST;
    return `${assetUrl}/public/images/${path}`;
}

const imageUrl = asset(currentUser.profil_picture);

When I use this code, the resulting imageUrl is incorrect, as it includes the React current path and localhost. Here's an example of the incorrect URL:

imageUrl = "http://localhost:5173/news_feed/127.0.0.1:8000/public/images/7c2bbd80-764e-4c6b-9be9-60cabc73b599.png"

How can I modify the asset() function to return only the correct localhost URL for the image location?

1

There are 1 best solutions below

0
Kia Boluki On

Actually you don't need get VITE_HOST . In Laravel you should store your images in storage/app/public folder instead of public folder. then you should create a link from public folder to storage/app/public folder.

you can do this by php artisan storage:link command.


so let's assume your image is in this path: storage/app/public/images/avatars/profile.jpg

and now you can get files in the public/storage/ folder like this:

const asset = (path) => {
    return `/storage/images/${path}`;
}

Usage:

<img src={asset('avatars/profile.jpg')} />