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

carlosoliveiras's avatar

Protected acess route

I need to validate user access to certain routes. Users have roles such as 'regular' and 'manager', and the regular user shouldn't be able to access routes specific to the manager.

0 likes
2 replies
tisuchi's avatar
tisuchi
Best Answer
Level 70

@carlosoliveiras I recommend that you use a middleware.

Here is my idea-

  1. Define your middleware, e.g. RoleMiddleware

public function handle($request, Closure $next, ...$roles)
{
    if (!auth()->check() || !in_array(auth()->user()->role, $roles)) {
        abort(403); // Forbidden
    }

    return $next($request);
}
  1. Register your middelware in the app/Http/Kernel.php (if needed)

  2. Apply middleware in the route:

Route::middleware(['auth', 'role:manager'])->group(function () {
    // Your routes.... 
});
2 likes
JussiMannisto's avatar

One built-in way is to use gates.

// Define gates in a service provider:
Gate::define('manage', fn (User $user) => $user->role === 'manager'));

// Authorization with middleware:
Route::post(...)->middleware('can:manage');

// Authorization in code:
if (!$user->can('manage'))
	abort(403);

Please or to participate in this conversation.