Laravel check for asset existence

12,231

Solution 1

It would be better to handle this from the webserver, as just because the file exists, doesn't mean it'll be accessible to the public web. Also means you're not repeating code all over the place to check if the file exists see: Replace invalid image url with 404 image

However this can be done PHP wise

@if (file_exists(public_path('path/to/asset.png')))
    <img src="{{ asset('path/to/asset.png') }}">
@else
    <img src="{{ asset('path/to/missing.png') }}">
@endif

Solution 2

Well aside from using native php methods here

You could use:

if (File::exists($myfile)){ ... }

However, you should note that asset(...) will return an absolute URL to the asset, but you need to check its existence on the file system, so you'll need a path like:

$img = path('public').'/path/to/image.png';
Share:
12,231
Alex
Author by

Alex

Updated on June 09, 2022

Comments

  • Alex
    Alex almost 2 years

    I would like to check whether an asset {{ asset }} exists before trying to output the file.

    I have tried a few things after some google-ing, but none seem to work on Laravel 5.0.

    An example of what i would imagine the request (in a frontend blade view) to look like;

    @if(asset(path-to-asset))
       <img src="image-path"/>
    @else
       <img src="no-image-path"/>
    @endif
    

    Thanks