0
0
Laravelframework~10 mins

Why middleware filters requests in Laravel - Test Your Understanding

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

Complete the code to create a middleware that checks if a user is authenticated.

Laravel
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class Authenticate
{
    public function handle(Request $request, Closure $next)
    {
        if (!auth()->check()) {
            return redirect()->route('[1]');
        }
        return $next($request);
    }
}
Drag options to blanks, or click blank then click option'
Adashboard
Bhome
Clogin
Dregister
Attempts:
3 left
💡 Hint
Common Mistakes
Redirecting to 'home' or 'dashboard' instead of 'login'.
Using a URL instead of a route name.
2fill in blank
medium

Complete the middleware code to allow only users with 'admin' role to proceed.

Laravel
<?php

public function handle(Request $request, Closure $next)
{
    if ($request->user()->role !== '[1]') {
        abort(403);
    }
    return $next($request);
}
Drag options to blanks, or click blank then click option'
Auser
Badmin
Cguest
Deditor
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'user' or 'guest' instead of 'admin'.
Not aborting with 403 status code.
3fill in blank
hard

Fix the error in the middleware that should check if the request method is POST.

Laravel
<?php

public function handle(Request $request, Closure $next)
{
    if ($request->method() !== '[1]') {
        return redirect()->back();
    }
    return $next($request);
}
Drag options to blanks, or click blank then click option'
APOST
BGET
CPUT
DDELETE
Attempts:
3 left
💡 Hint
Common Mistakes
Checking for 'GET' instead of 'POST'.
Using uppercase or lowercase inconsistently.
4fill in blank
hard

Fill both blanks to create a middleware that filters requests with a specific header and aborts if missing.

Laravel
<?php

public function handle(Request $request, Closure $next)
{
    if (!$request->headers->has('[1]')) {
        abort([2]);
    }
    return $next($request);
}
Drag options to blanks, or click blank then click option'
AX-Auth-Token
BAuthorization
C404
D403
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Authorization' header instead of 'X-Auth-Token'.
Aborting with 404 instead of 403.
5fill in blank
hard

Fill all three blanks to create a middleware that filters requests by IP and method, aborting if conditions fail.

Laravel
<?php

public function handle(Request $request, Closure $next)
{
    if ($request->ip() !== '[1]' || $request->method() !== '[2]') {
        abort([3]);
    }
    return $next($request);
}
Drag options to blanks, or click blank then click option'
A192.168.1.1
BPOST
C403
DGET
Attempts:
3 left
💡 Hint
Common Mistakes
Using GET instead of POST for method check.
Using wrong IP address or abort code.