试图获取非对象的属性“ uid”

问题描述

在刀片中,我试图确定需要显示哪个按钮,但是出现以下错误: 试图获取非对象的属性“ uid”。

在我的Entry模型中,我建立了这种关系:

public function blockeduser() {
    return $this->hasOne(BlockedUser::class);
}

在我的BlockedUser模型中,我建立了这种关系:

public function entry() {
    return $this->belongsTo(Entry::class);
}

刀片文件中的代码

@foreach($entries as $entry)
<tr>
    <td style="max-width: 150px;">
        <div class="btn-group">
            <form target="_blank" method="post" action="{{route('entries.show',$entry->id)}}">
                @method("GET")
                <button style="margin-right: 5px;" type="submit" class="btn btn-success">View</button>
            </form>

            @if ($entry->uid !== $entry->blockeduser->uid)
                <form method="post" action="{{route('entries.blockUser',$entry->id)}}">
                    @csrf
                    <button style="margin-right: 5px;" type="submit" class="btn btn-warning">Block</button>
                </form>

            @else
                <form method="post" action="{{route('entries.unblockUser',$entry->id)}}">
                    @csrf
                    <button style="margin-right: 5px;" type="submit" class="btn btn-warning">Unblock</button>
                </form>
            @endif

            <form method="post" action="{{route('entries.destroy',$entry->id)}}">
                @csrf
                @method("DELETE")

                <button style="margin-right: 5px;" type="submit" class="btn btn-danger">Delete</button>
            </form>
        </div>
    </td>
</tr>
@endforeach

如何访问与条目有关系的阻止用户表中的uid,并对其进行比较并确定需要显示哪种表单。

还是有一种方法可以检查表中是否包含与条目有关系的行?

可能的解决方案吗?

因为找不到$entry->blockeduser->uid,所以我在刀片文件中编辑了if语句:

@if ($entry->blockeduser == null)
<form method="post" action="{{route('entries.blockUser',$entry->id)}}">
    @csrf
    <button style="margin-right: 5px;" type="submit" class="btn btn-warning">Block</button>
</form>

@elseif ($entry->blockeduser !== null)
<form method="post" action="{{route('entries.unblockUser',$entry->id)}}">
    @csrf
    <button style="margin-right: 5px;" type="submit" class="btn btn-warning">Unblock</button>
</form>
@endif

解决方法

检查$entry->blockeduser是否存在,然后再检查其中的uid,如下所示:

if ($entry->blockeduser instanceof \App\Models\BlockedUser && $entry->uid !== $entry->blockeduser->uid)
,

如果$entry 为null,则可以使用可选的全局帮助程序,不会抛出异常

optional($entry)->uid;

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...