目标:如果文件存在,请加载文件,否则加载default.png
。
我试过
@if(file_exists(public_path().'/images/photos/account/{{Auth::user()->account_id}}.png'))
<img src="/images/photos/account/{{Auth::user()->account_id}}.png" alt="">
@else
<img src="/images/photos/account/default.png" alt="">
@endif
结果
当我100%确定1002.png
存在时,它会继续加载我的默认图像。
如何正确检查该文件是否存在?
答案 0 :(得分:30)
尽可能地尝试减少if
语句的数量。例如,我会执行以下操作:
// User Model
public function photo()
{
if (file_exists( public_path() . '/images/photos/account/' . $this->->account_id . '.png')) {
return '/images/photos/account/' . $this->account_id .'.png';
} else {
return '/images/photos/account/default.png';
}
}
// Blade Template
<img src="{!! Auth::user()->photo() !!}" alt="">
使您的模板更干净,使用更少的代码。您还可以对此方法编写单元测试以测试您的语句: - )
答案 1 :(得分:15)
检查文件是否存在于&#34; File ::&#34;并将resut传递给视图
$result = File::exists($myfile);
答案 2 :(得分:10)
解决方案
@if(file_exists( public_path().'/images/photos/account/'.Auth::user()->account_id.'.png' ))
<img src="/images/photos/account/{{Auth::user()->account_id}}.png" alt="">
@else
<img src="/images/photos/account/default.png" alt="">
@endif
答案 3 :(得分:4)
在Laravel 5.5中,您可以在存储外观上使用exists
方法:
https://laravel.com/docs/5.5/filesystem
$exists = Storage::disk('s3')->exists('file.jpg');
您可以使用三元表达式:
$file = ($exists) ? Storage::disk('s3')->get('file.jpg') :
Storage::disk('s3')->get('default.jpg');
答案 4 :(得分:4)
@if(file_exists('uploads/users-pic/'.auth()->user()->code_melli.'.jpg'))
<img src="{{'/uploads/users-pic/'.auth()->user()->code_melli.'.jpg'}}"
class="img-circle" alt="{{auth()->user()->name}}" width="60" height="60">
@else
<img src="/assets/images/user-4.png" width="60" height="60" class="img-circle img-corona" alt="user-pic" />
@endif
正如您在上面的代码中看到的那样,当你想检查图像时,不要在你的第一个路径上使用'/'
@if(file_exists('uploads/users-pic/'.auth()->user()->code_melli.'.jpg'))
答案 5 :(得分:1)
将文件保存在数据库中。如果图像路径存在
<?php
$path = "packages/pathoffile/img/media/" . $filename;
$media = isset($media) ? $media : ""; //If media is saved
?>
@if($media == "")
<img src='../packages/defaultimagelocation/assets/img/user.png' />
@else
<img src='../packages/originalmedialocation/img/media{{ $media }}' />
@endif
答案 6 :(得分:1)
if( !(Storage::exists('order/'.$details['photo'])) )
{
Storage::copy($details['photo'], 'order/'.$details['photo']);
}
use Storage;
控制器顶部。