在null上调用成员函数can()

时间:2018-11-27 02:52:44

标签: php laravel

我正在使用Laravel 5.7,我正在遵循文档https://laravel.com/docs/5.7/authorization#via-blade-templates

@if(auth()->user()->can('update-properties') and $child_types)
     {!! Form::select('type_2', $type_2_options, null, ['placeholder' => __('places.none'), 'class' => 'custom-select custom-select-sm w-50']) !!}
@else

我得到了错误

  

在null上调用成员函数can()

我认为can()方法始终可用吗?当然,我不必在每次测试门之前都检查auth()-> user()是否为空吗?

4 个答案:

答案 0 :(得分:1)

如果用户返回null,则在这种情况下最有可能是因为用户未通过身份验证/已注销。 试试

  @if(!Auth::guest()) 

    @if(auth()->user()->can('update-properties') and $child_types)
     {!! Form::select('type_2', $type_2_options, null, ['placeholder' => __('places.none'), 'class' => 'custom-select custom-select-sm w-50']) !!}
    @else

     (rest of code here)

  @endif

答案 1 :(得分:1)

Use the Blade helpers for authorization checks,而不是直接在用户模型上调用它们。在您的示例中出现了错误,因为没有经过身份验证的用户,因此您在null上调用can

// Map directly to a model policy
@can('update', $property)
    //
@endcan

// Use custom action
@can('update-properties)
    //
@endcan

答案 2 :(得分:0)

实际上错误是Auth :: user()函数无法找到登录的用户...并且如果登录并再次收到错误,则意味着确保会话已过期。因为有时候我们在真诚工作的时候忘记了会话期满。 为了避免这种情况,使用身份验证中间件保护您的路由,也可以在控制器中使用它。因此,如果会话已过期并且您正在点击查看页面,它将自动带您进入登录屏幕。

答案 3 :(得分:0)

由于miken32,答案是@auth