In this blog, we’ll create and set up middleware in Laravel 11 to protect routes and manage admin authentication. Follow the step-by-step guide below.
Run the following command to generate middleware named Admin:

Step 1: Create Middleware

php artisan make:middleware Admin

This command creates a middleware file at app/Http/Middleware/Admin.php. Open the file and add the following logic:

if (Auth::guard('admin')->check()) {
return $next($request); // Allow access if the user is an admin
}
return redirect('/login'); // Redirect non-admin users to the login page

Step 2: Configure Guards in auth.php

To set up admin authentication, open the file config/auth.php and add the following configurations:
Guards
Add a new guard named admin under the guards section:

'admin' => [ 'driver' => 'session', 'provider' => 'admins', ],

Providers
Add a new provider for admins under the providers section:

'admins' => [ 'driver' => 'eloquent', 'model' => App\Models\Admin::class, ],

Ensure you have an Admin model created in the App\Models directory. If not, create it using:

php artisan make:model Admin

Step 3: Register Middleware Alias

Register the middleware in bootstrap/app.php by creating an alias. Add the following code:

->withMiddleware(function (Middleware $middleware) {
    $middleware->alias([
        'admin' => AdminOnly::class,
    ]);
})

The alias admin will allow us to use this middleware in routes.

Step 4: Create Admin Login Function

In your controller (e.g., FunctionController), add the following login function:

public function login(Request $request)
{
    $request->validate([
        'email' => 'required|email',
        'password' => 'required',
    ]);

    $credentials = $request->only('email', 'password');

    if (Auth::guard('admin')->attempt($credentials)) {
        // Redirect to admin dashboard upon successful login
        return redirect()->intended('/dashboard/admin');
    }

    return back()->withErrors([
        'email' => 'The provided credentials do not match our records.',
    ]);
}

Step 5: Create Admin Logout Function

In the same controller, add a logout function to log the admin out:

public function logout(Request $request)
{
    Auth::guard('admin')->logout(); // Log out the admin

    $request->session()->invalidate(); // Invalidate the session
    $request->session()->regenerateToken(); // Regenerate CSRF token

    return redirect('/login'); // Redirect to login page
}

Step 6: Protect Routes Using Middleware

Finally, protect routes using the admin middleware alias. Add the routes in routes/web.php:

Route::post('/login', [FunctionController::class, 'login']);
Route::get('/logout', [FunctionController::class, 'logout'])->name('logout');

Route::middleware(['admin'])->group(function () {
    Route::get('/dashboard/admin', function () {
        return view('admin.dashboard');
    });
});

Here, the admin middleware ensures that only authenticated admin users can access the /dashboard/admin route.

Conclusion

By following these steps, you can set up custom middleware in Laravel 11 to manage admin authentication. This approach ensures that only authenticated admin users have access to specific parts of your application. You can further customize this setup to include additional features like role-based access control.

Happy coding! 🚀

Categorized in:

Guides, Laravel,