【问题标题】:Trying to get property author of non-object error, how to fix it?试图获取非对象错误的属性作者,如何解决?
【发布时间】: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-&gt;replies-&gt;sortBydesc('id')-&gt;first() 正在返回 null,因此您试图获取属性 author 为 null。您需要添加检查或使用合并运算符,例如 $thread-&gt;replies-&gt;sortBydesc('id')-&gt;first()-&gt;author-&gt;avatar ?? '

标签: php laravel forum


【解决方案1】:

$thread-&gt;replies-&gt;sortBydesc('id')-&gt;first() 不知何故没有返回您正在寻找的最新回复,即使您已经在 if 语句中检查了$thread-&gt;replies。我会调试为什么无法检索到线程的最新回复,或者只是在 if 语句中添加另一个条件来检查它。

@if($thread->replies && $thread->replies->sortBydesc('id')->first())
  <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

【讨论】:

    猜你喜欢
    • 2020-02-23
    • 2019-03-11
    • 2018-08-22
    • 1970-01-01
    • 2020-03-01
    • 2018-11-18
    • 2017-03-02
    • 1970-01-01
    • 2018-05-23
    相关资源
    最近更新 更多