0
0
Laravelframework~30 mins

Creating middleware in Laravel - Try It Yourself

Choose your learning style9 modes available
Creating Middleware in Laravel
📖 Scenario: You are building a Laravel web application that needs to restrict access to certain routes based on user roles. Middleware is a way to filter HTTP requests entering your app.In this project, you will create a middleware that checks if a user is an admin before allowing access to admin routes.
🎯 Goal: Build a middleware in Laravel named CheckAdmin that blocks users who are not admins from accessing admin routes.
📋 What You'll Learn
Create a middleware class named CheckAdmin
Add a configuration variable adminRole with the value admin
Implement the handle method to check if the authenticated user's role matches adminRole
Return a redirect to /home if the user is not an admin, otherwise allow the request to proceed
💡 Why This Matters
🌍 Real World
Middleware is used in real Laravel apps to control access, add security checks, and modify requests before they reach your controllers.
💼 Career
Understanding middleware is essential for backend Laravel developers to implement authentication, authorization, and request filtering.
Progress0 / 4 steps
1
Create the middleware class
Create a middleware class named CheckAdmin inside the app/Http/Middleware directory with a handle method that accepts $request and $next parameters.
Laravel
Need a hint?

Use php artisan make:middleware CheckAdmin to generate the middleware class automatically, then open app/Http/Middleware/CheckAdmin.php to edit the handle method.

2
Add the admin role configuration variable
Inside the CheckAdmin class, add a protected property named adminRole and set it to the string 'admin'.
Laravel
Need a hint?

Declare a protected property adminRole inside the class and assign it the value 'admin'.

3
Implement the admin check logic
Inside the handle method, write an if statement that checks if the authenticated user's role is not equal to $this->adminRole. If so, return a redirect to /home. Otherwise, return $next($request) to allow the request to continue.
Laravel
Need a hint?

Use $request->user()?->role to get the current user's role safely. Redirect if not admin, else continue.

4
Register the middleware in the kernel
Open app/Http/Kernel.php and add the CheckAdmin middleware to the $routeMiddleware array with the key 'check.admin'.
Laravel
Need a hint?

Register your middleware with a key in the $routeMiddleware array so you can use it in routes.