目标:如果文件存在,则加载该文件,否则加载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
存在时,它会不断加载我的默认图像。
如何正确检查该文件是否存在?
最佳答案
尽可能减少 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="">
使您的模板更干净并使用更少的代码。您还可以对此方法编写单元测试来测试您的语句:-)
关于php - 确定 Laravel 5 中文件是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34028575/