Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel check for asset existence

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

like image 201
Alex Avatar asked May 08 '15 16:05

Alex


2 Answers

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
like image 170
Wader Avatar answered Nov 19 '22 05:11

Wader


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';
like image 1
fantasitcalbeast Avatar answered Nov 19 '22 03:11

fantasitcalbeast