11

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

jedrzej.kurylo
  • 39,591
  • 9
  • 98
  • 107
Alex
  • 2,003
  • 4
  • 19
  • 30

3 Answers3

24

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
Wader
  • 9,427
  • 1
  • 34
  • 38
  • In your first sentence, do you mean *client*? – lukasgeiter May 08 '15 at 16:24
  • @lukasgeiter no, the webserver (Apache, Nginx, etc.) is correct. Basically the same behaviour from the webserver, checks if the file exists, if not, rewrites to serve a "404 image" placeholder. – Wader May 08 '15 at 16:28
  • Thanks @Wader. In this particular instance, handling the image 404 in the view is more appropriate. Great answer, thanks – Alex May 08 '15 at 19:49
1

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';
laminatefish
  • 5,197
  • 5
  • 38
  • 70
0

Try this way: For Laravel:

<?php
                        $image = parse_url($user->image);
                        if(isset($image['host'])){
                             $image= $user->image;
                            }
                        else if($image==null){ 
                            $image= Request::root().'/uploads'.'/subsystems_icons/'.'democp.jpg';   
                        }
                        else {
                            $image= Request::root().'/uploads/'.$user->image;
                        }
                    ?>
                   
                <div class="">
                    <img class="image" style="width: 100%; height: 300px; object-fit: contain ;"
                        src="{{$image}}">
                </div>
Maizied Hasan Majumder
  • 1,197
  • 1
  • 12
  • 25