Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to define a middleware class in Laravel.
Laravel
class CheckAge { public function handle($request, Closure [1]) { // middleware logic } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'request' as the second parameter instead of 'next'.
Omitting the Closure parameter.
✗ Incorrect
The handle method receives the request and a Closure called next to pass the request further.
2fill in blank
mediumComplete the code to allow the request to proceed in the middleware.
Laravel
public function handle($request, Closure $next) {
return [1]($request);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Returning $request directly instead of calling $next.
Calling a function named 'next' without the $ sign.
✗ Incorrect
You must call the Closure $next with the $request to pass the request to the next middleware or controller.
3fill in blank
hardFix the error in the middleware to block users under 18 years old.
Laravel
public function handle($request, Closure $next) {
if ($request->age [1] 18) {
return redirect('home');
}
return $next($request);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>=' which allows underage users.
Using '==' which only blocks exactly 18.
✗ Incorrect
To block users under 18, check if age is less than 18.
4fill in blank
hardFill both blanks to create middleware that adds a header and passes the request.
Laravel
public function handle($request, Closure [1]) { $response = [2]($request); $response->headers->set('X-Custom-Header', 'MyValue'); return $response; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'next' without $ sign.
Using $response as the Closure parameter.
✗ Incorrect
The Closure parameter is $next and you call $next($request) to get the response.
5fill in blank
hardFill all three blanks to create middleware that checks a user role and redirects if unauthorized.
Laravel
public function handle($request, Closure [1]) { if ($request->user()->role [2] 'admin') { return [3]($request); } return redirect('unauthorized'); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '==' instead of '!=' to block unauthorized users.
Calling 'next' without $ sign.
✗ Incorrect
The Closure parameter is $next, check if role is not equal 'admin', then call $next($request).