Laravel 试图获得财产';用户';非对象拉威尔的研究

Laravel 试图获得财产';用户';非对象拉威尔的研究,laravel,Laravel,我有一个错误,我不明白为什么我会得到它。 我已经搜索了很多关于这个错误的线程,但没有找到与我对应的修复程序 外观\点火\异常\视图异常 正在尝试获取非对象的属性“user” 在模板刀片中的{{$contact->messages->last()->>user->name}行上(请参见下文) //在我的模板视图中: @foreach($contact\u列表为$contact) {{$contact->id} {{dd($contact->messages->last()->user->name)

我有一个错误,我不明白为什么我会得到它。 我已经搜索了很多关于这个错误的线程,但没有找到与我对应的修复程序

外观\点火\异常\视图异常 正在尝试获取非对象的属性“user”

在模板刀片中的
{{$contact->messages->last()->>user->name}
行上(请参见下文)

//在我的模板视图中:
@foreach($contact\u列表为$contact)
{{$contact->id}
{{dd($contact->messages->last()->user->name)}///这显示了一个好结果!
{{$contact->messages->last()->user->name}//这将向我显示Laravel错误
{{$contact->created_at->diffForHumans()}
{{$contact->updated_at->diffForHumans()}
@endforeach

谢谢。

最常见的原因是此链中的某些内容是空的。您可以使用
if
语句来防止错误。这是一种方法:

@if($contact->messages->last())
    @if($contact->messages->last()->user)
        {{ $contact->messages->last()->user->name }}
    @endif
@endif

听起来联系人没有消息,因此消息集合上的
last
将返回
null
,这不是一个对象。。。把一个
dd
放进你的循环不会有什么帮助,因为这只会向你展示第一次迭代,而不是死亡,你的循环可能会运行很多次迭代,而不仅仅是死亡one@lagbox我已编辑我的模板视图,请刷新您的页面。它使用dd()工作,但没有它就无法工作。使用dd it向我显示“SUNSHINE”,这是一个好的用户名。同样,一个循环可以运行多次,添加
dd
,dump and die,只需一次迭代就可以杀死它。错误不是来自第一次迭代,但每次使用
last()
查询数据库时,您都会忘记这里的错误。所以,我建议你加载你的关系,做一个没有括号的检查
// In my template view:
                @foreach($contact_list as $contact)
                  <tr>
                    <td>{{ $contact->id }}</td>
                    {{ dd($contact->messages->last()->user->name) }} // This display me the good result!
                    <td>{{ $contact->messages->last()->user->name }}</td> // This display me the Laravel error
                    <td>{{ $contact->created_at->diffForHumans() }}</td>
                    <td>{{ $contact->updated_at->diffForHumans() }}</td>
                  </tr>
                @endforeach
@if($contact->messages->last())
    @if($contact->messages->last()->user)
        {{ $contact->messages->last()->user->name }}
    @endif
@endif