仅在 "updated_at" 中对 null 调用成员函数 diffForHumans()

Call to a member function diffForHumans() on null only in "updated_at"

在我的 User 模型中,我有 created_atupdated_at 列。当我投 created_at 成功但当我投 updated_at 它 returns 下面的错误:

protected $appends = ['created_at_formatted', 'updated_at_formatted'];

public function getCreatedAtFormattedAttribute()
{
    return $this->created_at->diffForHumans();
}

public function getUpdatedAtFormattedAttribute()
{
    return $this->updated_at->diffForHumans();
}

尝试显示它 return $user; 它有效并同时显示。 但是当它到达 view 它返回一个错误 (我的视图是空白页):

Method App\User::__toString() must not throw an exception, caught Error: Call to a member function diffForHumans() on null

我控制器中的代码:

public function show(\App\User $user)
{
    $messages = auth()->user()->messages_to($user);

    return $user; //if I uncomment this line it works and displays all the formatted dates BUT when I comment, it returning an error above

    return view('messages.show', compact(['user', 'messages']));
}

问题很少,$appends包括created_at_formatted、'updated_at_formatted`、

您需要将访问器更改为 getCreatedAtFormattedAttribute(), 这样你就可以得到 ->created_at_formatted.

diffForHumans是Carbon

的方法

By default, Eloquent will convert the created_at and updated_at columns to instances of Carbon, which provides an assortment of helpful methods, and extends the native PHP DateTime class.

但是,你的updated_at的值是可以为空的,所以它没有转换成Carbon,所以你不能使用diffForHuman,试试这样:

protected $appends = ['created_at_formatted', 'updated_at_formatted'];

public function getCreatedAtFormattedAttribute()
{
    if ($this->created_at) {
        return $this->created_at->diffForHumans();
    } else {
        return "";
    }
}

public function getUpdatedAtFormattedAttribute()
{
    if ($this->updated_at) {
        return $this->updated_at->diffForHumans();
    } else {
        return "";
    }
}