首页 > 解决方案 > 如何检查数据库中的图像名称并在 Laravel Blade 模板中为 NULL 时返回静态图像?

问题描述

如何使用 Null 合并运算符检查数据库中的图像名称,否则返回静态图像?以下是我正在尝试使用的 Laravel Blade 文件中的一行。

<img src="{{ URL::asset('/images/user/'. $profile->photo ?? 'Firefighter-Silhouette.png') }}" class="rounded-circle shadow-2 img-thumbnail" alt="">

它不仅不返回静态图像,而且以某种方式删除了“/images/user/”字符串中的最后一个正斜杠。

<img src="https://siriusfireweb.local/images/user" class="rounded-circle shadow-2 img-thumbnail" alt="">

TIA

标签: phplaravellaravel-8laravel-blade

解决方案


第一个条件

 <img src="{{asset('/images/user/'. @if($profile->photo != null)
    {{ $profile->photo}}
    @else
    {{'Firefighter-Silhouette.png'}}
    @endif }}" class="rounded-circle shadow-2 img-thumbnail" alt="">
  • 您可以检查此代码,它可以帮助您找到空返回值。

第二个条件

@php 
if($profile->photo != null){ // you can check your condition here.
$img = asset('/images/user/'.$profile->photo);
}else{
$img = asset('/images/user/Firefighter-Silhouette.png');
}

@endphp

现在您可以在 img src 上使用 $img 变量


推荐阅读