设置在 Blade 中使用的获取记录默认值

Set fetched record default value for using in Blade

我尝试使用此方法从数据库中获取所有用户字段:

$user = Users::all();

我的数据库中有一些字段是 nullable 我想知道在 blade 中使用时是否有任何方法可以为空字段设置默认值?

例如我有这个字段:

first_name, last_name, bio, city, fb_account, twitter_account , ...

所有这些字段都是可选的(在数据库中可以为空)我想为具有空值的字段显示 N/A 但我不想对每个字段使用 @if

可能吗?

更新:

我想在任何地方使用 {{ $user->first_name }} 如果这是 null return N/A and ifnot null` return himself

您可以在 Laravel 5.4

中执行此操作
{{ $first_name or 'N/A' }}

一模一样
echo isset($first_name) ? $first_name : 'N/A'; 

根据您的更新,您可以查看 Accessor & Mutators

然后你可以这样:

public function getFirstNameAttribute($value)
{
    if(! empty($value)) 
    {
      return $value;
    }

    return null;
}

在将用户对象发送到视图之前使用 each 方法循环遍历用户对象

$user = Users::all()->each(function ($item, $key) {
    if ($item->first_name === null) {
        $item->first_name = 'N/A';
    }
});

如果你想这样做,你可以使用自定义属性

public function getFirstNameAttribute()
{
    return $this->first_name ?: 'N/A';
}

然后是

{{ $item->first_name }}