Bird
Raised Fist0
Laravelframework~20 mins

Creating middleware in Laravel - Practice Exercises

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!
❓ component_behavior
intermediate
2:00remaining
What is the output of this Laravel middleware?
Consider this middleware that checks if a user is an admin before allowing access. What will happen if a non-admin user tries to access a protected route?
Laravel
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class CheckAdmin
{
    public function handle(Request $request, Closure $next)
    {
        if (!$request->user() || !$request->user()->is_admin) {
            return redirect('/home');
        }
        return $next($request);
    }
}
AThe middleware throws a server error.
BThe user sees a 404 error page.
CThe user is allowed to proceed regardless of admin status.
DThe user is redirected to '/home' if not admin.
Attempts:
2 left
💡 Hint
Look at the condition inside the handle method and what happens when it fails.
📝 Syntax
intermediate
1:30remaining
Which middleware registration is correct in Laravel?
You want to register a middleware named 'CheckAge' to be used in routes. Which option correctly registers it in the HTTP kernel?
A'checkAge' => \App\Http\Middleware\CheckAge(),
B'check.age' => \App\Http\Middleware\CheckAge::class,
C'check_age' => new \App\Http\Middleware\CheckAge,
D'check-age' => 'App\Http\Middleware\CheckAge',
Attempts:
2 left
💡 Hint
Middleware classes are registered as class names, not instances or strings without ::class.
🔧 Debug
advanced
2:30remaining
Why does this middleware cause a 'Too many redirects' error?
This middleware redirects users to '/login' if they are not authenticated. However, users get stuck in a redirect loop. What is the cause?
Laravel
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class RedirectIfNotAuthenticated
{
    public function handle(Request $request, Closure $next)
    {
        if (!$request->user()) {
            return redirect('/login');
        }
        return $next($request);
    }
}
AThe middleware redirects '/login' requests back to '/login' causing a loop.
BThe middleware does not check if the user is authenticated correctly.
CThe middleware should use abort(401) instead of redirect.
DThe middleware is missing a return statement after redirect.
Attempts:
2 left
💡 Hint
Think about what happens when the user is already on the '/login' page.
❓ state_output
advanced
2:00remaining
What is the value of $request->header('X-Custom') after this middleware runs?
This middleware adds a custom header to the request before passing it on. What will be the value of the 'X-Custom' header in the next middleware or controller?
Laravel
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class AddCustomHeader
{
    public function handle(Request $request, Closure $next)
    {
        $request->headers->set('X-Custom', '12345');
        return $next($request);
    }
}
AThrows an error because headers are immutable
Bnull
C'12345'
D'x-custom'
Attempts:
2 left
💡 Hint
Headers can be modified on the request object before passing it on.
🧠 Conceptual
expert
1:30remaining
Which statement about Laravel middleware is true?
Choose the correct statement about how Laravel middleware works.
AMiddleware can modify the request before passing it to the controller and the response before sending it back.
BMiddleware only runs after the controller has processed the request.
CMiddleware cannot stop a request from reaching the controller once started.
DMiddleware must always return a JSON response.
Attempts:
2 left
💡 Hint
Think about the middleware handle method and the $next callback.

Practice

(1/5)
1. What is the primary purpose of middleware in Laravel?
easy
A. To define routes for the application
B. To filter and modify HTTP requests before they reach the controller
C. To create database migrations automatically
D. To generate views for the user interface

Solution

  1. Step 1: Understand middleware role

    Middleware acts as a filter that processes HTTP requests before they reach the controller or after the response leaves the controller.
  2. Step 2: Identify correct purpose

    Among the options, only filtering and modifying HTTP requests matches middleware's role.
  3. Final Answer:

    To filter and modify HTTP requests before they reach the controller -> Option B
  4. Quick Check:

    Middleware filters requests [OK]
Hint: Middleware filters requests before controllers [OK]
Common Mistakes:
  • Confusing middleware with routing
  • Thinking middleware creates database migrations
  • Assuming middleware generates views
2. Which command correctly creates a new middleware named CheckAge in Laravel?
easy
A. php artisan make:middleware CheckAge
B. php artisan create:middleware CheckAge
C. php artisan middleware:create CheckAge
D. php artisan generate:middleware CheckAge

Solution

  1. Step 1: Recall Laravel artisan command for middleware

    The correct command to create middleware is php artisan make:middleware Name.
  2. Step 2: Match the command with options

    Only php artisan make:middleware CheckAge uses the exact correct syntax.
  3. Final Answer:

    php artisan make:middleware CheckAge -> Option A
  4. Quick Check:

    Use 'make:middleware' to create middleware [OK]
Hint: Use 'make:middleware' with artisan to create middleware [OK]
Common Mistakes:
  • Using 'create:middleware' instead of 'make:middleware'
  • Mixing command order or keywords
  • Forgetting to specify middleware name
3. Given this middleware handle method, what will happen if the user is not authenticated?
public function handle($request, Closure $next) {
    if (!auth()->check()) {
        return redirect('login');
    }
    return $next($request);
}
medium
A. The request proceeds to the next middleware or controller
B. The request is blocked with a 403 Forbidden response
C. An error is thrown because of missing return
D. The user is redirected to the login page

Solution

  1. Step 1: Analyze the authentication check

    The code checks if the user is not authenticated using !auth()->check().
  2. Step 2: Understand the redirect action

    If not authenticated, it returns a redirect response to 'login', stopping further request processing.
  3. Final Answer:

    The user is redirected to the login page -> Option D
  4. Quick Check:

    Unauthenticated users get redirected [OK]
Hint: Redirect happens if auth check fails [OK]
Common Mistakes:
  • Assuming request proceeds despite failed auth
  • Thinking an error is thrown
  • Confusing redirect with 403 response
4. Identify the error in this middleware handle method:
public function handle($request, Closure $next) {
    if ($request->user()->role !== 'admin') {
        abort(403, 'Unauthorized');
    }
}
medium
A. No error, this middleware is correct
B. Incorrect method name, should be handleRequest
C. Missing return statement for $next middleware call
D. Using abort() is not allowed in middleware

Solution

  1. Step 1: Check middleware handle method structure

    Middleware must return either a response or call $next($request) to continue the request.
  2. Step 2: Identify missing return

    This code aborts if role is not admin but does not return $next($request) if the user is admin, causing no response to be returned.
  3. Final Answer:

    Missing return statement for $next middleware call -> Option C
  4. Quick Check:

    Always return $next($request) to continue [OK]
Hint: Always return $next($request) in middleware [OK]
Common Mistakes:
  • Forgetting to return $next($request)
  • Thinking abort() is disallowed
  • Renaming handle method incorrectly
5. You want to create middleware that blocks requests with a query parameter blocked=true by aborting with a 403 Forbidden response. Which handle method implementation correctly achieves this?
hard
A. public function handle($request, Closure $next) { if ($request->query('blocked') === 'true') { abort(403, 'Access denied'); } return $next($request); }
B. public function handle($request, Closure $next) { if ($request->input('blocked') == true) { return redirect('home'); } return $next($request); }
C. public function handle($request, Closure $next) { if ($request->blocked === true) { abort(404); } return $next($request); }
D. public function handle($request, Closure $next) { if ($request->has('blocked')) { return response('Blocked', 401); } return $next($request); }

Solution

  1. Step 1: Check how to read query parameters

    Use $request->query('blocked') to get the query parameter value as string.
  2. Step 2: Verify condition and response

    public function handle($request, Closure $next) { if ($request->query('blocked') === 'true') { abort(403, 'Access denied'); } return $next($request); } checks if 'blocked' equals string 'true' and aborts with 403, then returns next middleware call.
  3. Step 3: Compare other options

    public function handle($request, Closure $next) { if ($request->input('blocked') == true) { return redirect('home'); } return $next($request); } uses input() and redirects instead of aborting; public function handle($request, Closure $next) { if ($request->blocked === true) { abort(404); } return $next($request); } accesses property incorrectly; public function handle($request, Closure $next) { if ($request->has('blocked')) { return response('Blocked', 401); } return $next($request); } returns 401 but blocks any 'blocked' param regardless of value.
  4. Final Answer:

    Checks $request->query('blocked') === 'true' and uses abort(403, 'Access denied') -> Option A
  5. Quick Check:

    Use $request->query('blocked') and abort(403) [OK]
Hint: Use $request->query('param') and abort(403) to block [OK]
Common Mistakes:
  • Using $request->blocked instead of query()
  • Returning redirect instead of abort
  • Not checking exact 'true' string value
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