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

artisticre's avatar

Middleware Relationship

I know I am not referencing it correctly

User.php Relationship

public function roles(){
        return $this->belongsToMany('App\Models\Role');
    }

Role.php Relationship

public function users(){
        return $this->belongsToMany('App\Models\User');
    }

Middleware

<?php

namespace App\Http\Middleware;

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

class AdminMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        
        if(Auth::user()->roles->name !='admin')
        {
            toastr()->warning('You Do Not Have Admin Rights');
            return redirect()->back();
        }
        return $next($request);
    }
}

0 likes
3 replies
tykus's avatar

On the User model, the roles property (the result of the relationship) is a Collection of Role model instances. So, you will need to check if the Collection contains (or not) a Role with the given name. The Collection class has contains and doesntContain methods, e.g.

public function handle(Request $request, Closure $next): Response
{
    if($request->user->roles->doesntContain(fn(Role $role) => $role->name === 'admin'))
    {
        toastr()->warning('You Do Not Have Admin Rights');
        return redirect()->back();
    }
    return $next($request);
}

However, you don't need the Collection (and to hydrate all of those roles) at all; you can use the Query Builder to check for existence of a given record:

public function handle(Request $request, Closure $next): Response
{
    if($request->user->roles()->where('name', 'admin')->doesntExist())
    {
        toastr()->warning('You Do Not Have Admin Rights');
        return redirect()->back();
    }
    return $next($request);
}
artisticre's avatar

@tykus I did that and I get

Call to a member function roles() on null

I forgot to add here I have a pivot table role_user that stores the user_id and role_id

tykus's avatar

@artisticre you don’t have an authenticated user. Is the route also protected with an auth middleware

Please or to participate in this conversation.