Вызов функции-члена diffForHumans () для null только в "updated_at" - PullRequest
0 голосов
/ 28 января 2020

В моей модели User есть столбцы created_at и updated_at. Когда я разыгрываю created_at успешно, но когда я разыгрываю updated_at, он возвращает ошибку ниже:

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 , он возвращает ошибку (мой взгляд - пустая страница) :

Метод App \ User :: __ toString () не должен вызывать исключение, перехвачено Ошибка: вызов функции-члена diffForHumans () со значением 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']));
}

1 Ответ

0 голосов
/ 28 января 2020

Есть несколько проблем, $appends включает created_at_formatted, 'updated_at_formatted`,

, вам нужно изменить аксессор на getCreatedAtFormattedAttribute(), чтобы вы могли получить ->created_at_formatted.

diffForHumans - это метод Carbon

По умолчанию Eloquent преобразует столбцы create_at и updated_at в экземпляры Carbon, которые предоставляют набор полезных методов и расширяют собственный PHP Класс DateTime.

Однако ваше значение updated_at может иметь значение Nullable, поэтому оно не конвертируется в углерод, поэтому вы не можете использовать 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 "";
    }
}
...