Bird
Raised Fist0
Laravelframework~20 mins

Why middleware filters requests in Laravel - Challenge Your Understanding

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Middleware Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2: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?
ATo generate HTML views from controllers
BTo speed up database queries automatically
CTo check and modify requests before they reach the application logic
DTo store user data permanently on the server
Attempts:
2 left
💡 Hint
Think about how middleware can control access or change requests before the app handles them.
❓ component_behavior
intermediate
2:00remaining
What happens if middleware denies a request?
In Laravel, if a middleware decides a request should not proceed, what happens next?
AThe request is logged but still processed normally
BThe request continues to the controller but with a warning
CThe middleware crashes the application
DThe request is stopped and a response is sent back immediately
Attempts:
2 left
💡 Hint
Middleware can block requests to protect the app.
❓ state_output
advanced
2: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');
}
A"Hello"
Bnull
C"x-custom-header"
DThrows an error
Attempts:
2 left
💡 Hint
Middleware can add or change headers before the controller sees the request.
📝 Syntax
advanced
2: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?
A
public function handle($request, Closure $next) {
    if (!auth()-&gt;check()) {
        return redirect('login');
    }
    return $next($request);
}
B
public function handle($request, Closure $next) {
    if (auth()-&gt;user()) {
        return redirect('login');
    }
    return $next($request);
}
C
public function handle($request, Closure $next) {
    if (auth()-&gt;guest()) {
        return redirect('login');
    }
    return $next($request);
}
D
public function handle($request, Closure $next) {
    if (auth()-&gt;check) {
        return redirect('login');
    }
    return $next($request);
}
Attempts:
2 left
💡 Hint
Check the correct method to verify authentication and syntax for method calls.
🔧 Debug
expert
3: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);
}
AIt uses the wrong method to check authentication
BIt redirects authenticated users instead of unauthenticated ones
CIt does not return the next middleware
DIt throws a syntax error because of missing semicolons
Attempts:
2 left
💡 Hint
Look carefully at the condition and who it redirects.

Practice

(1/5)
1. What is the main purpose of middleware in a Laravel application?
easy
A. To filter and check requests before they reach the app
B. To store data permanently in the database
C. To create user interface components
D. To compile CSS and JavaScript files

Solution

  1. Step 1: Understand middleware role

    Middleware acts as a gatekeeper that processes requests before they reach the main app logic.
  2. Step 2: Identify main purpose

    Its main job is to filter, check, or modify requests to protect or control access.
  3. Final Answer:

    To filter and check requests before they reach the app -> Option A
  4. Quick Check:

    Middleware filters requests = D [OK]
Hint: Middleware acts before app logic to filter requests [OK]
Common Mistakes:
  • Confusing middleware with database storage
  • Thinking middleware builds UI components
  • Assuming middleware compiles assets
2. Which of the following is the correct way to apply middleware to a route in Laravel?
easy
A. $router->get('/home')->middleware('auth');
B. Route::get('/home')->middleware('auth');
C. Route::get('/home')->useMiddleware('auth');
D. $router->get('/home')->use('auth');

Solution

  1. Step 1: Recall Laravel route syntax

    Laravel uses the Route facade with methods like get() and middleware() to assign middleware.
  2. Step 2: Identify correct chaining method

    The correct method to apply middleware is middleware(), not useMiddleware() or use().
  3. Final Answer:

    Route::get('/home')->middleware('auth'); -> Option B
  4. Quick Check:

    Correct middleware method = C [OK]
Hint: Use Route::get()->middleware('name') to apply middleware [OK]
Common Mistakes:
  • Using $router instead of Route facade
  • Using useMiddleware() instead of middleware()
  • Using use() which is not a Laravel method
3. Given this middleware that blocks requests without a 'token' header, what will happen if a request lacks the token?
public function handle($request, Closure $next) {
    if (!$request->hasHeader('token')) {
        return response('Unauthorized', 401);
    }
    return $next($request);
}
medium
A. The request is stopped with a 401 Unauthorized response
B. The request is redirected to the login page
C. The request proceeds normally to the app
D. The request causes a server error

Solution

  1. Step 1: Analyze middleware condition

    The middleware checks if the request has a 'token' header; if not, it returns a 401 response immediately.
  2. Step 2: Understand request flow

    Without the token header, the middleware stops the request and sends back 'Unauthorized' with status 401.
  3. Final Answer:

    The request is stopped with a 401 Unauthorized response -> Option A
  4. Quick Check:

    Missing token header = 401 response [OK]
Hint: Middleware returns 401 if token header missing [OK]
Common Mistakes:
  • Assuming request proceeds without token
  • Thinking it redirects instead of returning 401
  • Expecting a server error instead of controlled response
4. This middleware is intended to block requests without 'X-API-KEY' header. What is wrong with it?
public function handle($request, Closure $next) {
    if ($request->header('X-API-KEY') == null) {
        $next($request);
    }
    return response('Forbidden', 403);
}
medium
A. It never calls $next() for valid requests
B. It should return 401 instead of 403
C. It uses wrong header name case
D. It returns 403 even when the header exists

Solution

  1. Step 1: Trace middleware logic

    If header is null, it calls $next($request) but does not return it, so execution continues.
  2. Step 2: Identify flow error

    After calling $next(), it always returns 403 response, so even valid requests get blocked.
  3. Final Answer:

    It returns 403 even when the header exists -> Option D
  4. Quick Check:

    Missing return before $next causes wrong 403 always [OK]
Hint: Always return $next($request) to continue request [OK]
Common Mistakes:
  • Not returning $next() call
  • Misunderstanding header case sensitivity (Laravel handles case)
  • Confusing 401 and 403 status codes
5. You want to create middleware that only allows requests with a 'role' header set to 'admin' or 'editor'. Which code snippet correctly implements this filter?
hard
A. public function handle($request, Closure $next) { if ($request->header('role') === 'admin' && $request->header('role') === 'editor') { return $next($request); } return response('Forbidden', 403); }
B. public function handle($request, Closure $next) { if ($request->header('role') == 'admin' || 'editor') { return $next($request); } return response('Forbidden', 403); }
C. public function handle($request, Closure $next) { if (in_array($request->header('role'), ['admin', 'editor'])) { return $next($request); } return response('Forbidden', 403); }
D. public function handle($request, Closure $next) { if ($request->header('role') != 'admin' || $request->header('role') != 'editor') { return response('Forbidden', 403); } return $next($request); }

Solution

  1. Step 1: Understand role check logic

    The middleware should allow requests if the 'role' header is either 'admin' or 'editor'.
  2. Step 2: Evaluate each option's condition

    public function handle($request, Closure $next) { if (in_array($request->header('role'), ['admin', 'editor'])) { return $next($request); } return response('Forbidden', 403); } uses in_array() correctly to check if role is in allowed list. public function handle($request, Closure $next) { if ($request->header('role') == 'admin' || 'editor') { return $next($request); } return response('Forbidden', 403); } has incorrect condition syntax. public function handle($request, Closure $next) { if ($request->header('role') === 'admin' && $request->header('role') === 'editor') { return $next($request); } return response('Forbidden', 403); } requires role to be both 'admin' and 'editor' simultaneously, which is impossible. public function handle($request, Closure $next) { if ($request->header('role') != 'admin' || $request->header('role') != 'editor') { return response('Forbidden', 403); } return $next($request); } logic is inverted and will block valid roles.
  3. Final Answer:

    Uses in_array() to correctly filter 'admin' or 'editor' roles -> Option C
  4. Quick Check:

    Use in_array() for multiple allowed values [OK]
Hint: Use in_array() to check multiple allowed roles [OK]
Common Mistakes:
  • Using || incorrectly without full comparisons
  • Checking for both roles with && instead of ||
  • Inverting logic causing wrong blocking
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard