Laravel 检查资产是否存在

Laravel check for asset existence

我想在尝试输出文件之前检查资产 {{ asset }} 是否存在。

我在一些 google-ing 之后尝试了一些东西,但是 none 似乎在 Laravel 5.0 上工作。

我想象中的请求(在前端 blade 视图中)的示例;

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

谢谢

除了使用本机 php 方法 here

您可以使用:

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

但是,您应该注意 asset(...) 将 return 绝对 URL 资产,但您需要检查其在文件系统上的存在,因此您需要像这样的路径:

$img = path('public').'/path/to/image.png';

最好从网络服务器处理这个问题,因为文件存在并不意味着 public 网络可以访问它。也意味着您不会到处重复代码来检查文件是否存在,请参阅:Replace invalid image url with 404 image

然而这可以做到 PHP 明智

@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

试试这个方法: 对于 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>