【问题标题】:(1/1) FatalErrorException Call to a member function hasPermissionTo() on null in ClearanceMiddleware.php line 17(1/1) FatalErrorException 在 ClearanceMiddleware.php 第 17 行中调用 null 上的成员函数 hasPermissionTo()
【发布时间】:2018-10-27 07:23:57
【问题描述】:

https://scotch.io/tutorials/user-authorization-in-laravel-54-with-spatie-laravel-permission.

我已按照上述链接为用户设置角色和权限作为参考。

我收到错误:

(1/1) FatalErrorException
Call to a member function hasPermissionTo() on null

in ClearanceMiddleware.php line 17

我的数据库表是 This is my db table

清仓中间件代码为:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class ClearanceMiddleware {
    /**
    * Handle an incoming request.
    *
    * @param  \Illuminate\Http\Request  $request
    * @param  \Closure  $next
    * @return mixed
    */
    public function handle($request, Closure $next) {        
        if (Auth::user()->hasPermissionTo('Administer roles & permissions')) //If user has this //permission
    {
        return $next($request);
    }

    if ($request->is('posts/create'))//If user is creating a post
    {
        if (!Auth::user()->hasPermissionTo('Create Post'))
    {
        abort('401');
    } 
    else {
             return $next($request);
         }
    }

    if ($request->is('posts/*/edit')) //If user is editing a post
    {
        if (!Auth::user()->hasPermissionTo('Edit Post')) {
            abort('401');
        } else {
            return $next($request);
        }
    }

    if ($request->isMethod('Delete')) //If user is deleting a post
    {
        if (!Auth::user()->hasPermissionTo('Delete Post')) {
             abort('401');
        } 
        else 
        {
            return $next($request);
        }
    }

    return $next($request);
    }
}

请清除这个。

【问题讨论】:

    标签: php laravel permissions roles laravel-permission


    【解决方案1】:

    您似乎没有登录到您的应用程序。所以用户是空的,并且在空上调用成员函数会给出错误。

    你可以使用:

    $user = Auth::user();
    
    if(isset($user)){
      // Check for permission
    }
    

    除此之外,您还必须定义角色,并将这些角色分配给您的用户 在检查权限之前。 (我假设你已经完成了这些。)

    使用具有权限的用户登录,然后重试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-29
      • 1970-01-01
      • 1970-01-01
      • 2013-06-12
      • 1970-01-01
      • 1970-01-01
      • 2017-08-09
      相关资源
      最近更新 更多