Search code examples
phplaravelimagelaravel-5laravel-7

Return Response Image in Laravel 7


I'm trying to create a mini random image generator, as a start I've tried :

Route::get('/img/UoJb9wl.png','Image@random');

All I did is to return this

return '<img src="/assets/fe/img/welcome.jpeg" alt="Smiley face" width="200">';

Then, I tested on the live site :

I see the image loaded if I go to the URL

https://www.bunlongheng.com/img/UoJb9wl.png

enter image description here

If I imported on a site like JSFiddle like this

<img src="https://www.bunlongheng.com/img/UoJb9wl.png">

I can't see it.

Why ?


Edit

Try #2

return env('APP_URL').'/assets/fe/img/welcome.jpeg';

I return image path now

But I still nothing rendering in my JSFiddle still

<img src="https://www.bunlongheng.com/img/UoJb9wl.png">


Solution

  • This is not working just because of the returning image source <img src="/assets/fe/img/welcome.jpeg" alt="Smiley face" width="200"> is not available on your JSFiddle, even it will not work on any other website because no one have the image on this relative path /assets/fe/img/welcome.jpeg. If you want to really do that you have to specify the full absolute path. <img src="https://www.bunlongheng.com/assets/fe/img/welcome.jpeg" alt="Smiley face" width="200">.

    So your return statement could be.

    return '<img src="env('APP_URL')/assets/fe/img/welcome.jpeg" alt="Smiley face" width="200">';
    

    Or whatever you think is good to specify the absolute path.

    Further Explanation

    I have checked on the JSFiddle source code, you are using this link https://www.bunlongheng.com/img/UoJb9wl.png in the image src tag. It will not work at all if you even specify the absolute path.

    <img src="https://www.bunlongheng.com/img/UoJb9wl.png">
    

    When browser will try to populate the src tag it will send request to https://www.bunlongheng.com/img/UoJb9wl.png and the response code is <img src="/assets/fe/img/welcome.jpeg" alt="Smiley face" width="200"> so browser will populate it like this.

    <img src="<img src="/assets/fe/img/welcome.jpeg" alt="Smiley face" width="200">">
    

    So you have to return only the image path in the request, if you want to use this route in the image's src.

    return env('APP_URL')."/assets/fe/img/welcome.jpeg"
    

    If you want to keep your return statement same with image tag, then you can't use that route in image's src. Just use in the div or any other html tag.