Discover how one simple layer can save you hours of repetitive coding and bugs!
Creating middleware in Laravel - Why You Should Know This
Imagine you have to check if a user is logged in and has permission on every page manually by adding the same code in every controller method.
Manually adding checks everywhere is repetitive, easy to forget, and makes your code messy and hard to maintain.
Middleware lets you write this check once and apply it automatically to any route or group of routes, keeping your code clean and consistent.
if (!auth()->check()) { return redirect('login'); } // repeated in every controller method
Route::middleware('auth')->group(function () { Route::get('/dashboard', [DashboardController::class, 'index']); });
You can easily control access and modify requests globally without repeating yourself.
Protecting admin pages so only logged-in users with admin rights can access them, all handled by middleware.
Middleware centralizes request checks and modifications.
It prevents code duplication and errors.
It makes your app more secure and easier to maintain.
Practice
Solution
Step 1: Understand middleware role
Middleware acts as a filter that processes HTTP requests before they reach the controller or after the response leaves the controller.Step 2: Identify correct purpose
Among the options, only filtering and modifying HTTP requests matches middleware's role.Final Answer:
To filter and modify HTTP requests before they reach the controller -> Option BQuick Check:
Middleware filters requests [OK]
- Confusing middleware with routing
- Thinking middleware creates database migrations
- Assuming middleware generates views
CheckAge in Laravel?Solution
Step 1: Recall Laravel artisan command for middleware
The correct command to create middleware isphp artisan make:middleware Name.Step 2: Match the command with options
Only php artisan make:middleware CheckAge uses the exact correct syntax.Final Answer:
php artisan make:middleware CheckAge -> Option AQuick Check:
Use 'make:middleware' to create middleware [OK]
- Using 'create:middleware' instead of 'make:middleware'
- Mixing command order or keywords
- Forgetting to specify middleware name
public function handle($request, Closure $next) {
if (!auth()->check()) {
return redirect('login');
}
return $next($request);
}Solution
Step 1: Analyze the authentication check
The code checks if the user is not authenticated using!auth()->check().Step 2: Understand the redirect action
If not authenticated, it returns a redirect response to 'login', stopping further request processing.Final Answer:
The user is redirected to the login page -> Option DQuick Check:
Unauthenticated users get redirected [OK]
- Assuming request proceeds despite failed auth
- Thinking an error is thrown
- Confusing redirect with 403 response
public function handle($request, Closure $next) {
if ($request->user()->role !== 'admin') {
abort(403, 'Unauthorized');
}
}Solution
Step 1: Check middleware handle method structure
Middleware must return either a response or call$next($request)to continue the request.Step 2: Identify missing return
This code aborts if role is not admin but does not return$next($request)if the user is admin, causing no response to be returned.Final Answer:
Missing return statement for $next middleware call -> Option CQuick Check:
Always return $next($request) to continue [OK]
- Forgetting to return $next($request)
- Thinking abort() is disallowed
- Renaming handle method incorrectly
blocked=true by aborting with a 403 Forbidden response. Which handle method implementation correctly achieves this?Solution
Step 1: Check how to read query parameters
Use$request->query('blocked')to get the query parameter value as string.Step 2: Verify condition and response
public function handle($request, Closure $next) { if ($request->query('blocked') === 'true') { abort(403, 'Access denied'); } return $next($request); } checks if 'blocked' equals string 'true' and aborts with 403, then returns next middleware call.Step 3: Compare other options
public function handle($request, Closure $next) { if ($request->input('blocked') == true) { return redirect('home'); } return $next($request); } uses input() and redirects instead of aborting; public function handle($request, Closure $next) { if ($request->blocked === true) { abort(404); } return $next($request); } accesses property incorrectly; public function handle($request, Closure $next) { if ($request->has('blocked')) { return response('Blocked', 401); } return $next($request); } returns 401 but blocks any 'blocked' param regardless of value.Final Answer:
Checks $request->query('blocked') === 'true' and uses abort(403, 'Access denied') -> Option AQuick Check:
Use $request->query('blocked') and abort(403) [OK]
- Using $request->blocked instead of query()
- Returning redirect instead of abort
- Not checking exact 'true' string value
Ready to prove it?
Pass the test and this pattern moves unknown
