首页 > 解决方案 > ErrorException (E_ERROR) 试图获取非对象的属性“标题”

问题描述

ErrorException (E_ERROR) 试图获取非对象的属性“标题”(查看:D:\xampp\htdocs\xampp\practice\freecode\resources\views\profiles\index.blade.php)

以前的例外

试图获取非对象的属性“标题”(0)

            <div class="d-flex">
                <div ><strong>{{ $user->posts->count() }}</strong> posts</div>
                <div class="pl-5"><strong>23k</strong> followers</div>
                <div class="pl-5"><strong>435</strong> following</div>
            </div>
            <div class="pt-4 font-weight-bold" ><strong>{{ $user->profile->title }}</strong></div>
            <div>{{ $user->profile->description }}</div>
            <div><a href="#">{{ $user->profile->url ??'N/A' }}</a></div>
    </div>

</div>
<div class="row pt-5">
    @foreach($user->posts as $post)
    <div class="col-4" >
        <img src="/storage/{{ $post->image }}" class="w-100"> 
    </div>
    @endforeach

发布后显示此错误。

标签: phplaravel

解决方案


如果您清楚地阅读了错误消息,则表明您正在尝试访问空对象上的标题。这意味着以下关系为空。

 $user->profile // returns null

处理此错误的一种快速方法是使用空合并运算符。这将检查任何时候的第一条语句是否返回 null,如果不是,则返回第一条语句。否则它会退回到第二个语句。

{{ $user->profile->title ?? 'user not found'; }}

推荐阅读