Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Desssha's avatar

ErrorException: Attempt to read property "roleName" on null in file

ErrorException: Attempt to read property "roleName" on null in file

C:\xampp\htdocs\eraasoftBackendWorkshop\app\Http\Middleware\Roles.php on line 24

i make rout when i login as admin and send token in postman it work without problem but if login as support or secretary and and send token and try make update or anything show me this error

and this my middleware

namespace App\Http\Middleware;

use App\Http\Traits\ApiDesignTrait;

use Closure;

use Illuminate\Http\Request;

use ApiResponse;

class Roles { use ApiDesignTrait;

/**

 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request

 * @param  \Closure  $next

 * @return mixed

/* */

public function handle(Request $request, Closure $next, $roles)
{
    $userRole = auth()->user()->roleName->name;


    $allowUser = explode ('.',$roles);

    if(!in_array($userRole , $allowUser)){

        return $this->ApiResponse(422,' OOPS Not Allow for you not your Job');
    }
    return $next($request);
}

}

0 likes
5 replies
Braunson's avatar

Your formatting is messed up but the error it returns is pretty straightforward.

roleName is not available on null. Meaning auth()->user() is returning null.

Since this looks like your trying to access it via an API request which are session-less, you'll have to change how you access the current user via the API. If you look at the app\Http\Kernel.phpfile you'll see that on only the 'web' middleware group there is a StartSessionwhich is what allows you to access auth()->user(). Since your api middleware group doesn't have this, you cannot access the "current session".

There are ways around like Passport, and others, a quick google will help you along :)

Ref: https://github.com/laravel/laravel/blob/8.x/app/Http/Kernel.php

Desssha's avatar

i make rout when i login as dmin and send token in postman it work without problem but if login as support and and send token and try make update or anything show me this error

Desssha's avatar

i already register it in kernel.php . when i use admin everthing work good but if secertary or support can't do anyting

kevin@lio's avatar

i am facing the same erroor and still don't know how to solve it,

1 like
Snapey's avatar

@kevin@lio start by asking your own question with your own circumstances

Please or to participate in this conversation.