0
0
Laravelframework~10 mins

Creating middleware in Laravel - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
Aresponse
Brequest
Cnext
Dmiddleware
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'request' as the second parameter instead of 'next'.
Omitting the Closure parameter.
2fill in blank
medium

Complete 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'
A$request
B$next
Cnext
Dhandle
Attempts:
3 left
💡 Hint
Common Mistakes
Returning $request directly instead of calling $next.
Calling a function named 'next' without the $ sign.
3fill in blank
hard

Fix 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'
A<
B>=
C==
D!=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>=' which allows underage users.
Using '==' which only blocks exactly 18.
4fill in blank
hard

Fill 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'
A$next
Bnext
C$response
Dhandle
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'next' without $ sign.
Using $response as the Closure parameter.
5fill in blank
hard

Fill 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'
A$next
B!=
D==
Attempts:
3 left
💡 Hint
Common Mistakes
Using '==' instead of '!=' to block unauthorized users.
Calling 'next' without $ sign.