当用户未登录时获取错误,因为Auth :: user() - > hasRole('Admin')`无法检查用户是否在Laravel中具有admin角色

时间:2018-02-06 20:12:33

标签: php laravel

我有一个标签可用作图像的删除按钮,但是,在我的刀片模板中,我只将按钮显示给图像的上传者或网站的管理员。遗憾的是,当用户未登录时,我收到错误,因为Auth::user()->hasRole('Admin')无法检查用户是否具有admin角色。知道怎么回避这个问题吗?

错误:

"Call to a member function hasRole() on null"

我的代码

<div class="wrapper">
    <div class='imageContainer'>
        <h1 class='imageTitle'>{{$image->name}}</h1>
        <div class="stickyImageContainer">
            <img class='uploadedRealImage' src='/storage/images/uploaded/{{$image->file_name}}' alt='Random image'/>
            @if (Auth::id() === $image->user_id || Auth::user()->hasRole('Admin'))
                <div class='deleteImageButton'></div>
                <a class='deleteImageA' href='{{ route('deleteImage', ['image_id' => $image->id]) }}'>X</a>
            @endif
        </div>
    </div>
</div>

2 个答案:

答案 0 :(得分:1)

您需要先检查Auth::user()是退回模型还是null首先退回:

@if (Auth::id() === $image->user_id || (Auth::user() && Auth::user()->hasRole('Admin')))

将这些分成两个嵌套可能更清晰:

@if(Auth::user())
    @if(Auth::id() === $image->user_id || Auth::user()->hasRole('Admin'))

甚至更好,使用Laravel's authorization gates来包含这个逻辑,这将允许您这样做:

@can('delete', $image)

答案 1 :(得分:1)

在尝试访问用户角色之前使用auth()->check()

@if(auth()->check()  && Auth::user()->hasRole('Admin'))
    ....
@endif

Laravel还提供cancannot刀片指令。请参阅:https://laravel.com/docs/5.5/authorization#via-blade-templates