Laravel 5.8 @if(Auth :: user()&& Auth :: user()-> role_id == 2)返回错误

时间:2019-11-24 16:39:25

标签: laravel authentication laravel-blade

我在导航栏上遇到的问题:

@if(Auth::user()->role_id && Auth::user()->role_id == 2)
    <a class="dropdown-item" href="/">Manage My Ad Images</a>
    <a class="dropdown-item" href="/">My Ads</a>
    <a class="dropdown-item" href="/">Post an Ad</a>
    <a class="dropdown-item" href="/">Reload My Account</a>
@endif

我收到“试图获取非对象的属性'role_id'”错误。

我也尝试过Auth :: check(),但没有区别。

@if(Auth::check() && Auth::user()->role_id && Auth::user()->role_id == 2)
    <a class="dropdown-item" href="/">Manage My Ad Images</a>
    <a class="dropdown-item" href="/">My Ads</a>
    <a class="dropdown-item" href="/">Post an Ad</a>
    <a class="dropdown-item" href="/">Reload My Account</a>
@endif

1 个答案:

答案 0 :(得分:1)

首先检查是否存在带有@if(Auth::check())的经过身份验证的用户,然后嵌套其他条件:

@if(Auth::check())
    @if(Auth::user()->role_id && Auth::user()->role_id == 2)
        <a class="dropdown-item" href="/">Manage My Ad Images</a>
        <a class="dropdown-item" href="/">My Ads</a>
        <a class="dropdown-item" href="/">Post an Ad</a>
        <a class="dropdown-item" href="/">Reload My Account</a>
    @endif
@endif