Bird
Raised Fist0
Laravelframework~20 mins

Global middleware in Laravel - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Laravel Middleware Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when a global middleware returns a response early?

In Laravel, if a global middleware returns a response before calling $next($request), what is the effect on the request lifecycle?

Laravel
public function handle($request, Closure $next)
{
    if ($request->header('X-Block')) {
        return response('Blocked by middleware', 403);
    }
    return $next($request);
}
AThe request stops and the response is sent immediately, skipping all other middleware and the controller.
BThe request continues to the next middleware but the response is ignored.
CThe middleware throws an error because it must always call $next($request).
DThe middleware modifies the request but the response is delayed until the controller finishes.
Attempts:
2 left
💡 Hint

Think about what happens if middleware returns a response without calling the next middleware.

📝 Syntax
intermediate
2:00remaining
Identify the syntax error in this global middleware registration

Which option correctly registers a global middleware in Laravel's app/Http/Kernel.php file?

Laravel
protected $middleware = [
    \App\Http\Middleware\CheckAge::class,
];
A
protected $middleware = [
    App\Http\Middleware\CheckAge::class,
];
B
protected $middleware = [
    \App\Http\Middleware\CheckAge::class,
];
C
protected $middleware = [
    'App\Http\Middleware\CheckAge',
];
D
protected $middleware = [
    \App\Http\Middleware\CheckAge::class
];
Attempts:
2 left
💡 Hint

Remember the correct way to reference a class with namespace in PHP arrays.

❓ state_output
advanced
2:00remaining
What is the output after applying this global middleware?

Given this global middleware that adds a header, what will the client receive?

Laravel
public function handle($request, Closure $next)
{
    $response = $next($request);
    $response->headers->set('X-Global', 'Active');
    return $response;
}
AThe response does not include the <code>X-Global</code> header because headers cannot be modified after $next.
BThe middleware causes a runtime error because headers are immutable.
CThe response includes the header <code>X-Global: Active</code>.
DThe response includes the header <code>X-Global</code> but with an empty value.
Attempts:
2 left
💡 Hint

Think about how middleware can modify the response after calling $next.

🔧 Debug
advanced
2:00remaining
Why does this global middleware not run for some routes?

Consider this global middleware registered in Kernel.php. It does not run for routes using the 'api' middleware group. Why?

Laravel
protected $middleware = [
    \App\Http\Middleware\CheckUser::class,
];

protected $middlewareGroups = [
    'web' => [
        // web middleware
    ],
    'api' => [
        'throttle:api',
        'auth:api',
    ],
];
AThe 'api' middleware group does not include global middleware, but global middleware runs for all routes regardless.
BGlobal middleware always runs for all routes; the issue is elsewhere.
CThe middleware is registered globally but the 'api' routes use a different HTTP kernel instance.
DThe 'api' middleware group overrides global middleware, so global middleware is skipped.
Attempts:
2 left
💡 Hint

Recall how Laravel applies global middleware versus middleware groups.

🧠 Conceptual
expert
2:00remaining
How does Laravel prioritize global middleware compared to route middleware?

In Laravel, when a request is handled, in what order are global middleware and route middleware executed?

AGlobal middleware run only if route middleware allow the request to proceed.
BRoute middleware run first, then global middleware, then controller.
CGlobal and route middleware run simultaneously in parallel before the controller.
DGlobal middleware run first, then route middleware, then controller.
Attempts:
2 left
💡 Hint

Think about the middleware layers and their scope in Laravel.

Practice

(1/5)
1. What is the main purpose of global middleware in a Laravel application?
easy
A. To run code on every HTTP request to the application
B. To handle database migrations automatically
C. To define routes for the application
D. To manage user sessions only on login

Solution

  1. Step 1: Understand what middleware does

    Middleware acts as a filter or layer that runs code before or after a request is handled.
  2. Step 2: Identify the role of global middleware

    Global middleware runs on every HTTP request, applying tasks like authentication or logging universally.
  3. Final Answer:

    To run code on every HTTP request to the application -> Option A
  4. Quick Check:

    Global middleware = runs on every request [OK]
Hint: Global middleware affects all requests, not just some [OK]
Common Mistakes:
  • Confusing middleware with routing
  • Thinking middleware only runs on login
  • Assuming middleware manages database
2. Which file in a Laravel project is used to register global middleware?
easy
A. config/app.php
B. routes/web.php
C. app/Http/Kernel.php
D. app/Providers/AppServiceProvider.php

Solution

  1. Step 1: Recall where middleware is registered

    Middleware is registered in the Kernel class which manages HTTP middleware stacks.
  2. Step 2: Identify the correct Kernel file

    In Laravel, the HTTP Kernel is located at app/Http/Kernel.php where global middleware is listed in the $middleware array.
  3. Final Answer:

    app/Http/Kernel.php -> Option C
  4. Quick Check:

    Global middleware registered in Kernel.php [OK]
Hint: Middleware registration is in Kernel.php, not routes or config [OK]
Common Mistakes:
  • Choosing routes/web.php which defines routes only
  • Confusing config/app.php with middleware registration
  • Selecting service providers which are for services
3. Given this snippet in app/Http/Kernel.php:
$middleware = [
    \App\Http\Middleware\CheckAge::class,
];
What happens when a user sends a request to the app?
medium
A. The CheckAge middleware runs only on POST requests
B. The CheckAge middleware runs on every request
C. The CheckAge middleware runs only on routes with 'age' prefix
D. The CheckAge middleware does not run automatically

Solution

  1. Step 1: Understand the $middleware array role

    The $middleware array in Kernel.php lists global middleware that runs on every request.
  2. Step 2: Analyze the effect of adding CheckAge middleware there

    Since CheckAge is in $middleware, it will execute on all HTTP requests regardless of method or route.
  3. Final Answer:

    The CheckAge middleware runs on every request -> Option B
  4. Quick Check:

    $middleware = global middleware runs always [OK]
Hint: Middleware in $middleware runs on all requests, no exceptions [OK]
Common Mistakes:
  • Thinking middleware runs only on certain HTTP methods
  • Assuming middleware runs only on specific routes
  • Believing middleware must be manually attached to routes
4. You added a new global middleware class to $middleware in app/Http/Kernel.php, but it does not run on requests. What is the most likely cause?
medium
A. The middleware class is registered in $routeMiddleware instead of $middleware
B. The middleware class is not imported in routes/web.php
C. The middleware class is missing a constructor
D. The middleware class does not implement the handle method

Solution

  1. Step 1: Understand difference between $middleware and $routeMiddleware

    $middleware is for global middleware; $routeMiddleware is for middleware assigned to specific routes.
  2. Step 2: Identify why middleware won't run globally

    If middleware is only registered in $routeMiddleware, it won't run on every request unless assigned to routes.
  3. Final Answer:

    The middleware class is registered in $routeMiddleware instead of $middleware -> Option A
  4. Quick Check:

    Global middleware must be in $middleware array [OK]
Hint: Global middleware must be in $middleware, not $routeMiddleware [OK]
Common Mistakes:
  • Forgetting to implement handle method causes errors, not silent skip
  • Importing middleware in routes/web.php is unnecessary
  • Assuming constructor is required for middleware to run
5. You want to log every request's URL and method globally in your Laravel app. Which is the best way to do this using global middleware?
hard
A. Add logging code directly inside routes/web.php for each route
B. Register a route middleware and assign it to all routes manually
C. Use a controller constructor to log requests for each controller
D. Create a middleware with a handle method that logs request info and add it to $middleware in Kernel.php

Solution

  1. Step 1: Identify how to apply logging globally

    Global middleware runs on every request, perfect for logging all requests centrally.
  2. Step 2: Implement middleware and register globally

    Create middleware with a handle method that logs request URL and method, then add it to $middleware array in Kernel.php.
  3. Step 3: Evaluate other options

    Logging in routes or controllers is repetitive and error-prone; assigning route middleware to all routes is inefficient.
  4. Final Answer:

    Create a middleware with a handle method that logs request info and add it to $middleware in Kernel.php -> Option D
  5. Quick Check:

    Global logging = global middleware in $middleware [OK]
Hint: Use global middleware for app-wide request logging [OK]
Common Mistakes:
  • Logging inside routes causes duplication
  • Controller constructors don't cover all requests
  • Assigning route middleware manually is tedious and error-prone
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