Laravel check for asset existence
Asked Answered
S

3

12

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

Selfappointed answered 8/5, 2015 at 16:9 Comment(0)
A
25

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
Antisyphilitic answered 8/5, 2015 at 16:16 Comment(3)
In your first sentence, do you mean client?Ethnomusicology
@Ethnomusicology 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.Antisyphilitic
Thanks @Wader. In this particular instance, handling the image 404 in the view is more appropriate. Great answer, thanksSelfappointed
A
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';
Ascidium answered 8/5, 2015 at 16:16 Comment(0)
A
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>
Audet answered 22/10, 2020 at 7:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.