Validate access to routes according to Role using Middelware with Laravel

Viewed 42

The idea is to be able to define from the routes what type of user will be able to access the view. I have a code, but I don't know if there are any security problems doing it this way.

In the route, we would call the middelware and pass it the types of users that are allowed. ONLY THOSE THAT ARE ALLOWED.

Route::get('/MyURL', [MyClassController::class, 'MyMethod'])->name('MyName')->middleware('isAuthenticate:Role1,Role2');

And the middleware would be something like this

//The function receives the allowed roles and stores them in the variable $roles
public function handle(Request $request, Closure $next,...$roles)
{

  // Then loop through this variable and if any of the allowed roles match the user's role, continue... otherwise redirect to error-404
    for ($i=0; $i < count($roles); $i++) { 
        if($request->user()->role == $roles[$i]){
            return $next($request);
        }
    }

    return redirect('/error-404');
}

I don't know, it seems to me a simple and elegant way to do it. I don't know if there will be any security issues with this though.

1 Answers
Related