【发布时间】:2020-08-14 07:54:28
【问题描述】:
已尝试遵循本教程 Laravel show last reply left on post,工作正常,但现在在某些线程上返回此错误
Trying to get property 'author' of non-object (View: /var/www/html/web/resources/views/forums/board.blade.php)
这是我使用的代码:
<h1>{{$board->name}}</h1>
@auth
<a role="button" href="{{route('forums.thread.create', $board->id)}}" class="btn btn-primary">Create Thread</a>
@endauth
@foreach($board->threads->sortByDesc('pinned') as $thread)
<div class="thread-box {{$thread->pinned ? '' : 'bg-light'}} p-3 mt-3" style="background-color: #eee;">
<a href="{{route('forums.thread.show', $thread->id)}}" class="text-decoration-none">
<img src="{{$thread->author->avatar}}" alt="User Avatar" style="max-height: 40px;" class="rounded-circle">
<span>
{{$thread->name}}
</span>
</a>
@if(!$thread->pinned)
@else
<div class=" d-inline lock">
<i class="fas fa-thumbtack"></i>
</div>
@endif
@if(!$thread->locked)
@else
<div class=" d-inline lock">
<i class="fas fa-lock"></i>
</div>
@endif
<hr>
@if($thread->replies)<p>Last Update: <img src="{{$thread->replies->sortBydesc('id')->first()->author->avatar}}" alt="User Avatar" style="max-height: 40px;" class="rounded-circle"> <b>{{$thread->replies->sortBydesc('id')->first()->author->username}}</b></p>@else<p>No New Activity</p>@endif
</div>
@endforeach
</div>
@endsection
之前像我说的那样工作,但似乎不再工作了。有什么想法吗?
【问题讨论】:
-
这个错误已经足够明确了。
$thread->replies->sortBydesc('id')->first()正在返回 null,因此您试图获取属性author为 null。您需要添加检查或使用合并运算符,例如$thread->replies->sortBydesc('id')->first()->author->avatar ?? '