Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display an image if it exists or a default if it doesn't

Tags:

laravel

lumen

Trying to figure out how to display an image if it exists, or a default if it doesn't. Heres what I have so far, but the statement checking for the file doesn't seem to be working:

@if (file_exists(public_path('img/{{ $product->sku }}.jpg')))
    <img src="img/{{$product->sku}}.jpg">
@else
    <img src="img/logo.gif">
@endif

Heres my full blade code. Everything works except the image:

<div class="products-gallery">
    <h2>{{$product->prd->description_long}}</h2>
    <p><strong>ITEM SKU:</strong> {{$product->sku}}</p>  
    <p><strong>PRICE:</strong> {{$product->prd->Jobber}}</p>
    @if (file_exists(public_path('img/{{$product->sku}}.jpg')))
        <img src="img/{{$product->sku}}.jpg">
    @else
        <img src="img/logo.gif">
    @endif
</div>
like image 241
Casey Avatar asked Oct 26 '25 14:10

Casey


1 Answers

Although you asked about Laravel implementation, you should also be aware you can do it in pure javascript and avoid verifying the existence of the file:

<img src="img/{{$product->sku}}.jpg" onerror="this.onerror=null;this.src='img/logo.gif';" />

Less code to write and this will also handle other errors (such as file exists but corrupted).

Hope this helps.

like image 163
dev7 Avatar answered Oct 29 '25 19:10

dev7