Bird
Raised Fist0
Laravelframework~20 mins

Route 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 is the output when accessing a route with middleware that aborts on condition?
Consider a Laravel route with middleware that checks if a user is admin. If not, it aborts with 403. What happens when a non-admin user accesses this route?
Laravel
<?php

Route::middleware(['checkAdmin'])->get('/dashboard', function () {
    return 'Welcome Admin';
});

// Middleware checkAdmin
public function handle($request, Closure $next)
{
    if (! $request->user()?->isAdmin()) {
        abort(403, 'Unauthorized');
    }
    return $next($request);
}
AThe user receives a 403 Forbidden error page.
BThe user sees 'Welcome Admin' message.
CThe user is redirected to the login page.
DThe middleware throws a runtime exception.
Attempts:
2 left
💡 Hint
Think about what abort(403) does in Laravel middleware.
📝 Syntax
intermediate
2:00remaining
Which middleware registration syntax is correct in Laravel 10?
You want to register a route middleware named 'checkRole' in Laravel 10. Which syntax is correct in the RouteServiceProvider or routes file?
ARoute::middleware(['checkRole'])->group(function () { Route::get('/admin', fn() => 'Admin'); });
BRoute::middleware('checkRole', function () { Route::get('/admin', fn() => 'Admin'); });
CRoute::middleware(['checkRole', 'auth'])->get('/admin', fn() => 'Admin');
DRoute::middleware('checkRole')->group(function () { Route::get('/admin', fn() => 'Admin'); });
Attempts:
2 left
💡 Hint
Middleware names can be passed as a string or array, but group expects array for multiple.
❓ state_output
advanced
2:00remaining
What is the output of a route with multiple middleware modifying request data?
Given two middleware that add headers to the response, what headers will the client receive?
Laravel
<?php

// Middleware A
public function handle($request, Closure $next)
{
    $response = $next($request);
    return $response->header('X-Middleware-A', 'A');
}

// Middleware B
public function handle($request, Closure $next)
{
    $response = $next($request);
    return $response->header('X-Middleware-B', 'B');
}

Route::middleware(['middlewareA', 'middlewareB'])->get('/test', function () {
    return response('OK');
});
AResponse headers include only X-Middleware-A: A
BResponse headers include X-Middleware-A: A and X-Middleware-B: B
CResponse headers include only X-Middleware-B: B
DResponse has no custom headers
Attempts:
2 left
💡 Hint
Middleware run in order and can add headers to the response.
🔧 Debug
advanced
2:00remaining
Why does this middleware not stop unauthorized users?
This middleware is supposed to abort unauthorized users but does not. Why?
Laravel
<?php

public function handle($request, Closure $next)
{
    if (! $request->user()?->isAdmin()) {
        abort(403);
    }
    return $next($request);
}
Aabort(403) does not stop execution in Laravel middleware.
BMiddleware must call $next() before aborting.
CThe user() method is not available on the request object.
DThe middleware forgets to return the result of $next($request).
Attempts:
2 left
💡 Hint
Middleware must return the next middleware's response.
🧠 Conceptual
expert
2:00remaining
How does Laravel determine the order of middleware execution in a route?
Given a route with middleware ['auth', 'log', 'throttle'], in what order are the middleware executed and why?
AMiddleware run randomly depending on server load.
BMiddleware run in reverse order: throttle, then log, then auth.
CMiddleware run in the order listed: auth, then log, then throttle.
DMiddleware run in parallel, order does not matter.
Attempts:
2 left
💡 Hint
Think about how middleware wrap the request in layers.

Practice

(1/5)
1. What is the main purpose of route middleware in Laravel?
easy
A. To run code before or after a route handles a request
B. To define database relationships
C. To create views for the application
D. To manage session storage

Solution

  1. Step 1: Understand middleware role

    Middleware runs code before or after a route processes a request to add extra logic.
  2. Step 2: Compare with other options

    Database relationships, views, and session storage are unrelated to middleware's main role.
  3. Final Answer:

    To run code before or after a route handles a request -> Option A
  4. Quick Check:

    Middleware = Pre/Post route code [OK]
Hint: Middleware runs code around route handling [OK]
Common Mistakes:
  • Confusing middleware with database or view logic
  • Thinking middleware manages sessions directly
  • Assuming middleware creates HTML views
2. Which of the following is the correct way to apply middleware named auth to a route in Laravel?
easy
A. Route::get('/dashboard', function () {})->middleware('auth');
B. Route::get('/dashboard', function () {}, 'auth');
C. Route::get('/dashboard', function () {})->useMiddleware('auth');
D. Route::get('/dashboard', function () {})->apply('auth');

Solution

  1. Step 1: Recall middleware syntax for routes

    Laravel uses ->middleware('name') to assign middleware to a route.
  2. Step 2: Check syntax

    Only Route::get('/dashboard', function () {})->middleware('auth'); uses the correct method. Others use non-existent methods like apply() and useMiddleware() or pass invalid extra arguments.
  3. Final Answer:

    Route::get('/dashboard', function () {})->middleware('auth'); -> Option A
  4. Quick Check:

    Correct middleware method = middleware() [OK]
Hint: Use ->middleware('name') after route definition [OK]
Common Mistakes:
  • Using non-existent methods like useMiddleware or apply
  • Placing middleware before route method incorrectly
  • Forgetting to pass middleware name as string
3. Given the route group below, what middleware will be applied to the /profile route?
Route::middleware(['auth', 'verified'])->group(function () {
    Route::get('/profile', function () {
        return 'User Profile';
    });
});
medium
A. No middleware applied
B. Only 'verified' middleware
C. Only 'auth' middleware
D. Both 'auth' and 'verified' middleware

Solution

  1. Step 1: Understand middleware groups

    Middleware array passed to middleware() applies all listed middleware to routes inside the group.
  2. Step 2: Check the group middleware list

    The group uses ['auth', 'verified'], so both middleware run on /profile route.
  3. Final Answer:

    Both 'auth' and 'verified' middleware -> Option D
  4. Quick Check:

    Group middleware = all listed middleware [OK]
Hint: Middleware array applies all listed middleware [OK]
Common Mistakes:
  • Assuming only first middleware applies
  • Thinking middleware arrays override each other
  • Ignoring middleware groups and only checking route
4. Identify the error in this middleware assignment:
Route::get('/settings', function () {
    return 'Settings';
})->middleware(auth);
medium
A. Middleware cannot be applied to GET routes
B. Middleware must be registered in the controller
C. Middleware name should be a string
D. Middleware should be applied using ->useMiddleware()

Solution

  1. Step 1: Check middleware argument type

    Middleware names must be passed as strings, e.g., 'auth', not bare words.
  2. Step 2: Verify other options

    Middleware can be applied to GET routes; no need for controller registration here; useMiddleware() is invalid.
  3. Final Answer:

    Middleware name should be a string -> Option C
  4. Quick Check:

    Middleware name = string in quotes [OK]
Hint: Always quote middleware names as strings [OK]
Common Mistakes:
  • Passing middleware name without quotes
  • Thinking middleware only works on POST routes
  • Using non-existent middleware methods
5. You want to apply a middleware named checkAge only to routes under /admin but exclude it from /admin/login. Which is the best way to do this in Laravel?
hard
A. Apply checkAge middleware globally and remove it from /admin/login
B. Apply checkAge middleware to the group /admin and add except for /admin/login
C. Apply checkAge middleware only to /admin/login route
D. Apply checkAge middleware to all routes except /admin

Solution

  1. Step 1: Understand middleware group usage

    Applying middleware to a route group covers all routes inside it.
  2. Step 2: Use 'except' to exclude specific routes

    Laravel allows excluding routes from middleware using 'except' in middleware definition or group.
  3. Step 3: Evaluate options

    Apply checkAge middleware to the group /admin and add except for /admin/login correctly applies middleware to /admin group and excludes /admin/login. Others apply middleware incorrectly or globally.
  4. Final Answer:

    Apply checkAge middleware to the group /admin and add except for /admin/login -> Option B
  5. Quick Check:

    Group middleware + except route = correct approach [OK]
Hint: Use middleware group with except to exclude routes [OK]
Common Mistakes:
  • Applying middleware only to excluded route
  • Applying middleware globally without exclusions
  • Excluding entire /admin instead of just /admin/login
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