Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save diegoglz-dev/3287231eb60e3c5e3f7b87ddfb49ca12 to your computer and use it in GitHub Desktop.

Select an option

Save diegoglz-dev/3287231eb60e3c5e3f7b87ddfb49ca12 to your computer and use it in GitHub Desktop.

Laravel 11 - Authentication for role

1º step: Create middleware

php artisan make:middleware RedirectIfNotAdmin
// in RedirectIfNotAdmin.php
public function handle(Request $request, Closure $next): Response
    {
        if (Auth::check() && Auth::user()->role_id != 1) {
            return redirect('/');
        }

        return $next($request);
    }
// ..

2º step: registered middleware

// in bootstrap/app.php
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->alias([
            'admin' => \App\Http\Middleware\RedirectIfNotAdmin::class
        ]);
    })
// ..

3º step: use the middlewere in our routes file

// in routes/web.php
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home')->middleware('auth', 'admin');
// ..

4º Enjoy! 🤗 Laravel Love!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment