0
0
Laravelframework~30 mins

Route middleware in Laravel - Mini Project: Build & Apply

Choose your learning style9 modes available
Laravel Route Middleware Setup
📖 Scenario: You are building a Laravel web application that has a special admin section. You want to make sure only authenticated users can access the admin routes.
🎯 Goal: Create a route middleware that checks if a user is authenticated before allowing access to the admin routes.
📋 What You'll Learn
Create a middleware class named CheckAuthenticated
Register the middleware in the HTTP kernel with the key auth.check
Apply the auth.check middleware to the /admin/dashboard route
Ensure the middleware redirects unauthenticated users to the /login page
💡 Why This Matters
🌍 Real World
Middleware is used in Laravel apps to control access and modify requests before they reach your routes or controllers.
💼 Career
Understanding middleware is essential for Laravel developers to implement security, logging, and request filtering in real projects.
Progress0 / 4 steps
1
Create the middleware class
Create a middleware class named CheckAuthenticated inside the app/Http/Middleware directory. The class should have a handle method that accepts $request, Closure $next, and returns $next($request).
Laravel
Need a hint?

Middleware classes go in app/Http/Middleware. The handle method is required and must return $next($request) to continue the request.

2
Add authentication check in middleware
Inside the handle method of CheckAuthenticated, add a condition to check if the user is not authenticated using auth()->check(). If not authenticated, redirect to /login. Otherwise, continue the request with $next($request).
Laravel
Need a hint?

Use auth()->check() to verify if the user is logged in. Redirect unauthenticated users to /login.

3
Register the middleware in HTTP kernel
Open app/Http/Kernel.php and add the middleware class \App\Http\Middleware\CheckAuthenticated::class to the $routeMiddleware array with the key 'auth.check'.
Laravel
Need a hint?

Register your middleware in the $routeMiddleware array in Kernel.php so you can use it in routes.

4
Apply middleware to admin route
In routes/web.php, create a route for /admin/dashboard that returns the string 'Admin Dashboard'. Apply the middleware 'auth.check' to this route using the middleware method.
Laravel
Need a hint?

Use Route::get() to define the route and chain ->middleware('auth.check') to apply your middleware.