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
Cleareance中间件代码是:
<?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);
}
}
请清除这一点。
答案 0 :(得分:1)
您似乎未登录自己的应用。因此user为null,并且在null上调用成员函数会产生错误。
您可以使用:
$user = Auth::user();
if(isset($user)){
// Check for permission
}
除此之外,您必须定义角色,并将这些角色分配给您的用户 在检查权限之前。 (我假设你已经完成了这些。)
使用具有权限的用户登录,然后重试。