Bird
Raised Fist0
Laravelframework~20 mins

Controller middleware in Laravel - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Controller Middleware Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when middleware is applied to a Laravel controller?
Consider a Laravel controller with middleware applied in its constructor. What is the effect of this middleware on the controller's methods?
Laravel
class PostController extends Controller {
    public function __construct() {
        $this->middleware('auth');
    }

    public function index() {
        return 'Posts list';
    }

    public function show($id) {
        return "Post $id";
    }
}
AAll methods in the controller require the user to be authenticated before running.
BOnly the index method requires authentication; other methods are public.
CMiddleware runs after the controller methods finish executing.
DMiddleware is ignored when applied in the constructor.
Attempts:
2 left
💡 Hint
Think about when middleware runs in the request lifecycle.
📝 Syntax
intermediate
2:00remaining
Which code correctly applies middleware only to specific controller methods?
You want to apply the 'auth' middleware only to the 'edit' and 'update' methods of a Laravel controller. Which code snippet does this correctly?
A
public function __construct() {
    $this->middleware('auth')->only(['edit', 'update']);
}
B
public function __construct() {
    $this->middleware('auth')->except(['edit', 'update']);
}
C
public function __construct() {
    $this->middleware('auth', ['only' => ['edit', 'update']]);
}
D
public function __construct() {
    $this->middleware(['auth'])->only('edit', 'update');
}
Attempts:
2 left
💡 Hint
Check the correct method chaining syntax for middleware restrictions.
🔧 Debug
advanced
2:00remaining
Why does this middleware not run on the 'show' method?
Given this controller code, why does the 'show' method not require authentication?
Laravel
class ArticleController extends Controller {
    public function __construct() {
        $this->middleware('auth')->except('show');
    }

    public function show($id) {
        return "Article $id";
    }

    public function edit($id) {
        return "Edit Article $id";
    }
}
ABecause the middleware name 'auth' is misspelled and ignored.
BBecause 'show' method has its own middleware overriding the constructor middleware.
CBecause middleware only runs on POST requests, and 'show' is a GET method.
DBecause the middleware is set to run on all methods except 'show', so 'show' is public.
Attempts:
2 left
💡 Hint
Look at the except method usage in middleware.
❓ state_output
advanced
2:00remaining
What is the output when middleware aborts the request?
If the 'auth' middleware aborts the request with a 403 error, what will the user see when accessing a protected controller method?
Laravel
Route::get('/dashboard', [DashboardController::class, 'index'])->middleware('auth');

class DashboardController extends Controller {
    public function index() {
        return 'Welcome to dashboard';
    }
}
AThe user sees a blank page because middleware does not handle errors.
BThe user sees a 403 Forbidden error page and the controller method is not executed.
CThe user sees 'Welcome to dashboard' because middleware runs after the method.
DThe user sees a 500 Internal Server Error because middleware crashed.
Attempts:
2 left
💡 Hint
Middleware can stop the request before the controller runs.
🧠 Conceptual
expert
2:00remaining
How does Laravel handle multiple middleware on a controller?
If a Laravel controller applies multiple middleware in its constructor like this: $this->middleware('auth'); $this->middleware('log'); In what order do these middleware run when a request hits a controller method?
AMiddleware run in reverse order: 'log' first, then 'auth'.
BMiddleware run in parallel, so order does not matter.
CMiddleware run in the order they are added: 'auth' first, then 'log'.
DOnly the last middleware added runs, earlier ones are ignored.
Attempts:
2 left
💡 Hint
Think about the middleware stack order in Laravel.

Practice

(1/5)
1. What is the main purpose of middleware in a Laravel controller?
easy
A. To connect the controller to the database
B. To define routes for the controller
C. To run code before or after controller methods for access control or modification
D. To create views for the controller

Solution

  1. Step 1: Understand middleware role

    Middleware acts as a filter that runs before or after controller methods to control access or modify requests/responses.
  2. Step 2: Differentiate from other controller tasks

    Defining routes, connecting to databases, or creating views are not middleware responsibilities.
  3. Final Answer:

    To run code before or after controller methods for access control or modification -> Option C
  4. Quick Check:

    Middleware controls access and actions around controller methods = A [OK]
Hint: Middleware filters requests before/after controller methods [OK]
Common Mistakes:
  • Confusing middleware with routing
  • Thinking middleware creates views
  • Assuming middleware connects to database
2. Which is the correct way to add middleware to a Laravel controller constructor?
easy
A. $this->middleware('auth');
B. middleware->add('auth');
C. addMiddleware('auth');
D. useMiddleware('auth');

Solution

  1. Step 1: Recall Laravel middleware syntax

    In Laravel controllers, middleware is added inside the constructor using $this->middleware('name');.
  2. Step 2: Check other options for syntax correctness

    Options A, C, and D do not follow Laravel's middleware syntax and will cause errors.
  3. Final Answer:

    $this->middleware('auth'); -> Option A
  4. Quick Check:

    Use $this->middleware() in constructor = B [OK]
Hint: Use $this->middleware('name') inside constructor [OK]
Common Mistakes:
  • Using incorrect method names
  • Calling middleware outside constructor
  • Missing $this keyword
3. Given this controller constructor code:
public function __construct() {
    $this->middleware('auth')->only('edit', 'update');
}

Which methods will have the 'auth' middleware applied?
medium
A. Only the edit and update methods
B. All methods except edit and update
C. All methods in the controller
D. No methods, syntax error

Solution

  1. Step 1: Understand the use of only() method

    The only('edit', 'update') limits middleware to run only on these two methods.
  2. Step 2: Confirm middleware application

    Middleware 'auth' applies only to 'edit' and 'update', other methods are unaffected.
  3. Final Answer:

    Only the edit and update methods -> Option A
  4. Quick Check:

    only() limits middleware to specified methods = D [OK]
Hint: only() applies middleware to listed methods only [OK]
Common Mistakes:
  • Confusing only() with except()
  • Assuming middleware applies to all methods
  • Thinking syntax causes error
4. Identify the error in this controller constructor:
public function __construct() {
    $this->middleware('auth')->except('index', 'show');
    $this->middleware('log');
}
medium
A. Middleware 'log' will override 'auth' middleware
B. You cannot call middleware twice in constructor
C. except() method requires array, not multiple arguments
D. No error; both middleware apply correctly

Solution

  1. Step 1: Check multiple middleware calls

    Laravel allows multiple middleware calls in constructor; they stack and apply in order.
  2. Step 2: Validate except() usage

    except() accepts multiple string arguments or an array; both are valid.
  3. Final Answer:

    No error; both middleware apply correctly -> Option D
  4. Quick Check:

    Multiple middleware calls and except() usage are valid = C [OK]
Hint: Multiple middleware calls stack; except() accepts multiple args [OK]
Common Mistakes:
  • Thinking multiple middleware calls override each other
  • Assuming except() needs array only
  • Believing syntax causes error
5. You want to apply the 'verified' middleware to all controller methods except 'index' and 'show', and also apply 'log' middleware only to 'store' and 'update'. Which constructor code correctly implements this using arrays?
hard
A. public function __construct() { $this->middleware('verified')->only('index', 'show'); $this->middleware('log')->except('store', 'update'); }
B. public function __construct() { $this->middleware('verified')->except(['index', 'show']); $this->middleware('log')->only(['store', 'update']); }
C. public function __construct() { $this->middleware('verified'); $this->middleware('log'); }
D. public function __construct() { $this->middleware('verified')->except('index', 'show'); $this->middleware('log')->only('store', 'update'); }

Solution

  1. Step 1: Apply 'verified' middleware except on 'index' and 'show'

    Use except() with array to exclude 'index' and 'show' from 'verified' middleware.
  2. Step 2: Apply 'log' middleware only on 'store' and 'update'

    Use only() with array to limit 'log' middleware to 'store' and 'update' methods.
  3. Step 3: Compare options

    public function __construct() { $this->middleware('verified')->except('index', 'show'); $this->middleware('log')->only('store', 'update'); } uses except() and only() with multiple string arguments (valid but less common). public function __construct() { $this->middleware('verified')->except(['index', 'show']); $this->middleware('log')->only(['store', 'update']); } uses arrays which is clearer and recommended. Options B and C do not match requirements.
  4. Final Answer:

    public function __construct() { $this->middleware('verified')->except(['index', 'show']); $this->middleware('log')->only(['store', 'update']); } -> Option B
  5. Quick Check:

    Use except() and only() with arrays for clarity = A [OK]
Hint: Use except() and only() with arrays for multiple methods [OK]
Common Mistakes:
  • Mixing only() and except() incorrectly
  • Not using arrays for multiple methods
  • Applying middleware to wrong methods
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