Laravel 检查资产是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30128297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:30:53  来源:igfitidea点击:

Laravel check for asset existence

laravellaravel-5blade

提问by Alex

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

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

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

在谷歌搜索之后,我尝试了一些东西,但似乎没有一个适用于 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

谢谢

回答by Wader

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

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

However this can be done PHP wise

但是,这可以通过 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

回答by fantasitcalbeastly

Well aside from using native phpmethods here

除了在这里使用本机php方法之外

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:

但是,您应该注意这asset(...)将返回资产的绝对 URL,但您需要检查它在文件系统上的存在,因此您需要一个类似以下的路径:

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