Raffi
Raffi

Reputation: 31

(1/1) FatalErrorException Call to a member function hasPermissionTo() on null in ClearanceMiddleware.php line 17

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

I have followed the above link for my reference to set roles and permissions to users.

I am getting the error:

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

in ClearanceMiddleware.php line 17

My db tables are This is my db table

Cleareance middleware code is:

<?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);
    }
}

Please clear this.

Upvotes: 2

Views: 4400

Answers (1)

rgucluer
rgucluer

Reputation: 65

It seems you are not logged in to your app. So user is null, and calling a member function on null gives the error.

You can use:

$user = Auth::user();

if(isset($user)){
  // Check for permission
}

Beyond that you must define roles , and assign these roles to your user before checking for permissions. ( I assume you have done these. )

Log in with a user with permissions, then try again.

Upvotes: 2

Related Questions