检查Laravel的Blade模板中文件是否存在

6

我有一个简单的问题 - 如何在Laravel的Blade模板中检查文件是否存在? 我尝试了:

@if(file_exists('/covers/1.jpg')) ok @endif

但是它不起作用(covers目录在/public中)。我还需要向函数提供一个变量($game->id)。不幸的是,...
@if(file_exists('/covers/'.$game->id.'.jpg')) ok @endif

无法工作。


如果您的安装在子目录中,则该绝对路径将无法工作,除非将您的子目录设置为文档根目录。例如,如果您在localhost/yoursite/public访问您的站点,则需要使用/yoursite/public/covers/1.jpg,因为localhost将是文档根目录。 - Jason Lewis
6个回答

28

对我来说这个方法有效,favicon.ico文件在public目录下。

@if(file_exists('favicon.ico')) 
  File exists
@else
  Could not find file
@endif

所以我认为你只需要使用@if(file_exists('covers/1.jpg'))


9
在 Laravel 4 中,您可以使用以下方法:
 @if (file_exists(public_path('covers/1.jpg')))

使用public_path来获取文件的物理路径。

谢谢,这对我很有帮助。 - jvv

1

在我的情况下,我需要知道 Blade 模板是否存在,而不是一些公共文件。在这种情况下,最好的选项是:

@if(\View::exists('some.view'))
  ...
@endif  

以下内容也可能有用:

@includeIf('view.name', ['variable' => 'data'])@includeWhen($condition, 'view.name', ['variable' => 'data'])

它已在 Laravel 8.0 中进行了测试。


0
在 Laravel 5.8 中,我像这样使用它:
@if (file_exists (public_path ('filename.ico'))))
  << true, because the file exists >>
@other
  << false, because the file couldn't be found >>
@end if

如果我使用 asset() 而不是 public_path(),它将无法正常工作。
使用 Public_path(),您将获得文件的物理路径(从公共文件夹中获取)。

0
@if (file_exists( 'public/images/user/'.$userData["avtar"]) ) 
     <a href="#"><img src="{{asset('images/user/'.$userData["avtar"])}}" alt="11"></a>

@else
     <a href="#"><img src="{{asset('bouts9/assets/images/profile/profile.png')}}" alt="Profile Picture"></a>

@endif

0

这应该可以在Laravel 8中使用

file_exists("assets/images/image.extension")

file_exists 直接查找公共路径,因此您可以直接从公共文件夹中传递路径


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接