Challenge - 5 Problems
Middleware Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate2:00remaining
Why does middleware filter requests in Laravel?
Middleware in Laravel acts like a gatekeeper for incoming requests. What is the main reason Laravel uses middleware to filter requests?
Attempts:
2 left
💡 Hint
Think about how middleware can control access or change requests before the app handles them.
✗ Incorrect
Middleware filters requests to check or modify them before they reach the main application. This helps with tasks like authentication, logging, or modifying headers.
❓ component_behavior
intermediate2:00remaining
What happens if middleware denies a request?
In Laravel, if a middleware decides a request should not proceed, what happens next?
Attempts:
2 left
💡 Hint
Middleware can block requests to protect the app.
✗ Incorrect
If middleware denies a request, it stops the request from going further and sends a response immediately, like a 403 error for unauthorized access.
❓ state_output
advanced2:00remaining
What is the output when middleware modifies a request header?
Consider a Laravel middleware that adds a custom header
X-Custom-Header: Hello to every request. What will the controller receive?Laravel
<?php
// Middleware handle method
public function handle($request, Closure $next) {
$request->headers->set('X-Custom-Header', 'Hello');
return $next($request);
}
// Controller method
public function index(Request $request) {
return $request->header('X-Custom-Header');
}Attempts:
2 left
💡 Hint
Middleware can add or change headers before the controller sees the request.
✗ Incorrect
The middleware sets the header before passing the request on, so the controller receives the modified header value "Hello".
📝 Syntax
advanced2:00remaining
Identify the correct middleware syntax to allow only authenticated users
Which middleware code snippet correctly checks if a user is authenticated and redirects if not?
Attempts:
2 left
💡 Hint
Check the correct method to verify authentication and syntax for method calls.
✗ Incorrect
Option A uses auth()->check() correctly to verify if the user is logged in. If not, it redirects to login. Other options have wrong methods or syntax.
🔧 Debug
expert3:00remaining
Why does this middleware not stop unauthenticated users?
Given this middleware code, why does it fail to block unauthenticated users?
Laravel
public function handle($request, Closure $next) {
if (auth()->check()) {
return redirect('login');
}
return $next($request);
}Attempts:
2 left
💡 Hint
Look carefully at the condition and who it redirects.
✗ Incorrect
The condition auth()->check() returns true for authenticated users, so it redirects them instead of blocking unauthenticated users. The logic is reversed.