0
0
Laravelframework~30 mins

Middleware parameters in Laravel - Mini Project: Build & Apply

Choose your learning style9 modes available
Middleware Parameters in Laravel
📖 Scenario: You are building a simple Laravel web application that restricts access to certain pages based on user roles. You want to create a middleware that accepts parameters to check the user's role before allowing access.
🎯 Goal: Build a Laravel middleware that accepts a role parameter and restricts access to routes based on that role.
📋 What You'll Learn
Create a middleware class named CheckRole
Add a parameter to the middleware to accept a role string
Use the parameter inside the middleware to check the authenticated user's role
Apply the middleware with a parameter to a route in routes/web.php
💡 Why This Matters
🌍 Real World
Middleware parameters are used in real Laravel applications to control access to routes based on user roles or permissions dynamically.
💼 Career
Understanding middleware parameters is essential for backend developers working with Laravel to implement secure and flexible access control.
Progress0 / 4 steps
1
Create the CheckRole middleware class
Create a middleware class named CheckRole inside the app/Http/Middleware directory with a handle method that accepts $request, Closure $next, and a $role parameter.
Laravel
Need a hint?

Define the middleware class and the handle method with the $role parameter.

2
Add a role check variable inside the middleware
Inside the handle method of CheckRole, create a variable named $userRole that gets the authenticated user's role using $request->user()->role.
Laravel
Need a hint?

Use $request->user()->role to get the current user's role and store it in $userRole.

3
Add role comparison logic to allow or deny access
In the handle method, add an if statement that checks if $userRole is not equal to $role. If so, return a redirect to /home. Otherwise, allow the request to continue by returning $next($request).
Laravel
Need a hint?

Use an if condition to compare roles and redirect if they don't match.

4
Apply the CheckRole middleware with a parameter to a route
In routes/web.php, add a route for /admin that uses the CheckRole middleware with the parameter admin. The route should return a simple string 'Welcome Admin'.
Laravel
Need a hint?

Use ->middleware('checkrole:admin') to apply the middleware with the role parameter.