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

Nababur's avatar
Level 43

Call to a member function roles() on null

My Admin Middleware :

class Admin { /** * Handle an incoming request. * * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next */ public function handle(Request $request, Closure $next): Response {

    $adminRole = Auth::user()->roles()->pluck('name');
    if ($adminRole->contains('admin')) {
        return $next($request);
       
    }


}

}

Model relationship user

public function roles(){
    return $this->belongsToMany(Role::class);
}
0 likes
3 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

The error "Call to a member function roles() on null" occurs when the Auth::user() method returns null, meaning that there is no authenticated user. To fix this issue, you need to ensure that the user is authenticated before accessing their roles.

Here's an updated version of the handle method in the Admin middleware that includes the necessary check:

public function handle(Request $request, Closure $next): Response
{
    if (Auth::check()) {
        $adminRole = Auth::user()->roles()->pluck('name');
        if ($adminRole->contains('admin')) {
            return $next($request);
        }
    }

    // Handle unauthorized access here
    abort(403, 'Unauthorized');
}

In this updated code, we first check if the user is authenticated using the Auth::check() method. If the user is authenticated, we proceed to retrieve their roles and check if they contain the 'admin' role. If the condition is true, we allow the request to proceed by calling $next($request). Otherwise, we abort the request with a 403 (Unauthorized) status code.

Make sure to import the necessary classes at the top of your file:

use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Closure;
use Illuminate\Support\Facades\Auth;

Remember to replace Role::class with the actual class name of your Role model if it's different.

I hope this helps! Let me know if you have any further questions.

Nababur's avatar
Level 43

@LaryAI

I don't have created any Role mode, i have to use the roles method in the user Model for the belongsToMany() relationship.

class User extends Authenticatable implements MustVerifyEmail {

public function roles(){
    return $this->belongsToMany(Role::class);
}

}

Nababur's avatar
Level 43

Thanks LaryAI, its working now... i have modified some code also.

Please or to participate in this conversation.