0
0
Laravelframework~30 mins

Registering middleware in Laravel - Mini Project: Build & Apply

Choose your learning style9 modes available
Registering Middleware in Laravel
📖 Scenario: You are building a Laravel web application that needs to check user roles before allowing access to certain pages.Middleware helps you run code before a request reaches your routes or controllers.
🎯 Goal: Learn how to register a custom middleware in Laravel and apply it to a route.
📋 What You'll Learn
Create a middleware class named CheckUserRole
Register the middleware in the app/Http/Kernel.php file
Apply the middleware to a route in routes/web.php
💡 Why This Matters
🌍 Real World
Middleware is used in real Laravel apps to control access, log requests, or modify responses before reaching controllers.
💼 Career
Understanding middleware registration and usage is essential for Laravel developers to implement security and request handling.
Progress0 / 4 steps
1
Create the CheckUserRole middleware class
Create a middleware class named CheckUserRole inside the app/Http/Middleware directory with a handle method that accepts $request and $next parameters.
Laravel
Need a hint?

Use the handle method to pass the request to the next middleware or controller.

2
Register the CheckUserRole middleware in Kernel
Open the app/Http/Kernel.php file and add the CheckUserRole::class to the $routeMiddleware array with the key 'check.user.role'.
Laravel
Need a hint?

Add the middleware to the $routeMiddleware array with a key you will use in routes.

3
Apply the middleware to a route
In the routes/web.php file, create a route for /dashboard that uses the check.user.role middleware.
Laravel
Need a hint?

Use the middleware method on the route to apply your middleware key.

4
Complete the middleware to check user role
Update the handle method in CheckUserRole middleware to check if the authenticated user's role is 'admin'. If not, redirect to /home. Otherwise, allow the request to continue.
Laravel
Need a hint?

Use Auth::check() to verify login and Auth::user()->role to check the role.