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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With