如何抑制 laravel blade 中的 "Call to a member function function() on null" 错误?

How to suppress "Call to a member function function() on null" error in laravel blade?

我在 blade 模板中有此代码:

{{ $birthday->format('m/d/Y') }}

当 $birthday 为 null 时出现此错误,如何抑制此异常?

我想在 $birthday 为 null 时显示空字符串,我尝试了这两种解决方案但没有成功:

{{ $birthday->format('m/d/Y') or '' }}

并且:

{{ @$birthday->format('m/d/Y') }}

有什么建议吗?我想要 blade 解决方案不在 eloquent 模型中...

试试这个:

{{isset($生日)? $生日->格式('m/d/Y') : '' }}

您可以使用 @if@elseif@else@endif 指令构造 blade if 语句。这些指令与其 PHP 对应指令的功能相同:

  @if($birthday)
    {{ $birthday->format('m/d/Y') }}
   @endif

注意:在 @foreach $x 中使用 @if 将为每个 $x 重复 if 语句 More about Laravel Blade

编辑

这就是您正在寻找的优雅解决方案

{{ $birthday->format('m/d/Y')  ?: '' }}

您可以使用 null coalesce 为变量设置默认值。

{{ $var ?? 'default' }}

或者如果你有 PHP <7

<?php isset($var) ? $var  : 'default'; ?>

{{ $var }}

使用三元运算符:

{{ is_null($birthday) ? '' : $birthday->format('m/d/Y') }}

来自 Eloquent 模型的日期 returns 一个 Carbon/Carbon 对象或 null 如果未设置。如果您希望日期不存在则为空字符串,您可以创建一个 accessor.

class Foo extends Eloquent {
    public function getBirthdayAttribute() {
        return isset($this->attributes['birthday']) && $this->attributes['birthday'] instanceof \DateTime ? $this->attributes['birthday']->format('m/d/Y') : '';
    }
}

我的解决方案是扩展 blade :

class AppServiceProvider extends ServiceProvider
{
    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        Blade::directive('datetime', function ($expression) {
            if($expression == null){
                return '';
            }else{
                return "<?php echo ($expression)->format('m/d/Y'); ?>";
            }
        });
    }

    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

我经常用

{{ $var->prop ? $var->prop->format('d/m/Y') : '' }}

所有其他答案都太复杂或无法工作,以防您需要对相关变量调用函数。 幸运的是 Laravel 有一个很好的技巧;你可以使用 optional 助手:

{{ optional($birthday)->format('m/d/Y') }}

自 Laravel 6 开始可用 https://laravel.com/docs/8.x/helpers#method-optional

从 PHP 8.0 开始,您可以使用 nullsafe operator (?->),当 $birthday 为 null 时,它将整个表达式转换为 null。

{{ $birthday?->format('m/d/Y') }}