Bird
Raised Fist0
Laravelframework~5 mins

Middleware parameters in Laravel

Choose your learning style10 modes available
Introduction

Middleware parameters let you send extra information to middleware. This helps middleware act differently based on what you pass.

You want to check user roles like admin or editor in one middleware.
You need to limit access to certain pages based on a condition.
You want to reuse the same middleware but with different rules.
You want to pass a value to control middleware behavior without writing new middleware.
Syntax
Laravel
Route::get('profile', function () {
    // ...
})->middleware('role:admin');
Parameters come after the middleware name, separated by a colon (:).
Multiple parameters are separated by commas (,).
Examples
This sends 'admin' as a parameter to the 'role' middleware.
Laravel
Route::get('dashboard', function () {
    // ...
})->middleware('role:admin');
This sends '18' to the 'checkAge' middleware to check minimum age.
Laravel
Route::get('settings', function () {
    // ...
})->middleware('checkAge:18');
This sends two parameters 'view' and 'edit' to the 'permission' middleware.
Laravel
Route::get('report', function () {
    // ...
})->middleware('permission:view,edit');
Sample Program

This middleware checks if the logged-in user has the role 'admin'. The role is passed as a parameter 'admin' to the middleware. If the user is not admin, it returns 'Access denied.' Otherwise, it shows 'Welcome Admin!'.

Laravel
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class CheckRole
{
    public function handle(Request $request, Closure $next, $role)
    {
        if ($request->user()?->role !== $role) {
            return response('Access denied.', 403);
        }
        return $next($request);
    }
}

// In routes/web.php

use Illuminate\Support\Facades\Route;

Route::middleware(['auth', 'checkRole:admin'])->get('/admin', function () {
    return 'Welcome Admin!';
});
OutputSuccess
Important Notes

Middleware parameters are strings by default. Convert them inside middleware if needed.

Use question mark operator (null safe) to avoid errors if user is not logged in.

Parameters help keep middleware flexible and reusable.

Summary

Middleware parameters let you customize middleware behavior easily.

Pass parameters after middleware name separated by colon and commas.

Use parameters inside middleware handle method to control logic.

Practice

(1/5)
1. What is the correct way to pass parameters to a middleware in Laravel's route definition?
easy
A. Pass parameters inside parentheses after the middleware name, like auth(admin, active)
B. Add parameters as query strings after the middleware name, like auth?role=admin&status=active
C. Use a colon after the middleware name, then list parameters separated by commas, like auth:admin,active
D. List parameters separated by spaces after the middleware name, like auth admin active

Solution

  1. Step 1: Understand Laravel middleware parameter syntax

    Laravel middleware parameters are passed after the middleware name using a colon, then parameters separated by commas.
  2. Step 2: Identify correct syntax in route definition

    The correct syntax is middleware('auth:admin,active'), matching Use a colon after the middleware name, then list parameters separated by commas, like auth:admin,active.
  3. Final Answer:

    Use a colon after the middleware name, then list parameters separated by commas, like auth:admin,active -> Option C
  4. Quick Check:

    Middleware parameters = colon + comma-separated [OK]
Hint: Remember: colon then commas separate middleware parameters [OK]
Common Mistakes:
  • Using parentheses instead of colon and commas
  • Passing parameters as query strings
  • Separating parameters by spaces
2. Which of the following is the correct syntax to access middleware parameters inside the handle method?
easy
A. Use $request->params() to get parameters
B. Use the third argument of handle method as ...$params
C. Use $next($request, $params) to pass parameters
D. Use $this->params property inside middleware

Solution

  1. Step 1: Recall middleware handle method signature

    Laravel middleware handle method accepts $request, $next, and optional parameters as variadic arguments.
  2. Step 2: Identify correct way to receive parameters

    Parameters are received as additional arguments after $next, typically using ...$params.
  3. Final Answer:

    Use the third argument of handle method as ...$params -> Option B
  4. Quick Check:

    Middleware parameters = variadic arguments in handle [OK]
Hint: Use ...$params after $next in handle method [OK]
Common Mistakes:
  • Trying to get parameters from $request object
  • Passing parameters to $next instead of receiving them
  • Using non-existent $this->params property
3. Given this middleware handle method:
public function handle($request, Closure $next, $role)
{
    if ($request->user()->role !== $role) {
        return redirect('home');
    }
    return $next($request);
}

And route middleware usage: middleware('checkRole:admin')
What happens if a user with role 'editor' accesses the route?
medium
A. The user is redirected to 'home' because roles don't match
B. The user proceeds to the route normally
C. A runtime error occurs due to missing parameters
D. The middleware ignores the role and allows access

Solution

  1. Step 1: Understand middleware logic with parameter

    The middleware compares the user's role with the passed parameter $role. If they differ, it redirects to 'home'.
  2. Step 2: Apply given user role and parameter

    User role is 'editor', parameter is 'admin', so roles don't match, triggering redirect.
  3. Final Answer:

    The user is redirected to 'home' because roles don't match -> Option A
  4. Quick Check:

    User role != parameter role = redirect [OK]
Hint: Mismatch role parameter causes redirect in middleware [OK]
Common Mistakes:
  • Assuming user proceeds despite role mismatch
  • Expecting runtime error due to parameters
  • Thinking middleware ignores parameters
4. Consider this middleware handle method:
public function handle($request, Closure $next, $status)
{
    if ($status !== 'active') {
        return redirect('inactive');
    }
    return $next($request);
}

And route middleware usage: middleware('checkStatus')
What error or behavior occurs?
medium
A. The middleware ignores the parameter and throws a syntax error
B. The middleware runs normally and allows access
C. The middleware redirects to 'inactive' always
D. A runtime error because the required parameter $status is missing

Solution

  1. Step 1: Check middleware parameter requirement

    The handle method requires a parameter $status, but the middleware is used without parameters.
  2. Step 2: Understand Laravel behavior on missing parameters

    Laravel throws a runtime error if a required middleware parameter is missing when called.
  3. Final Answer:

    A runtime error because the required parameter $status is missing -> Option D
  4. Quick Check:

    Missing middleware parameter = runtime error [OK]
Hint: Middleware parameters must be passed or error occurs [OK]
Common Mistakes:
  • Assuming middleware runs without parameters
  • Expecting redirect without parameter
  • Confusing syntax error with runtime error
5. You want to create a middleware that accepts multiple roles as parameters and allows access if the user has any of those roles. Which of the following handle method implementations correctly uses middleware parameters to achieve this?
hard
A.
public function handle($request, Closure $next, ...$roles)
{
    if (!in_array($request->user()->role, $roles)) {
        return redirect('home');
    }
    return $next($request);
}
B.
public function handle($request, Closure $next, $roles)
{
    if ($request->user()->role !== $roles) {
        return redirect('home');
    }
    return $next($request);
}
C.
public function handle($request, Closure $next, $roles)
{
    foreach ($roles as $role) {
        if ($request->user()->role === $role) {
            return $next($request);
        }
    }
    return redirect('home');
}
D.
public function handle($request, Closure $next, ...$roles)
{
    if ($request->user()->role === $roles) {
        return $next($request);
    }
    return redirect('home');
}

Solution

  1. Step 1: Understand variadic parameters usage

    Using ...$roles collects all passed roles into an array for easy checking.
  2. Step 2: Check role membership logic

    Using in_array checks if user's role is in the roles array, allowing access if true.
  3. Step 3: Evaluate other options

    public function handle($request, Closure $next, $roles)
    {
        if ($request->user()->role !== $roles) {
            return redirect('home');
        }
        return $next($request);
    }
    treats roles as single string, not multiple; C expects $roles as array but parameters are strings; D compares string to array directly, which fails.
  4. Final Answer:

    Use ...$roles and in_array($request->user()->role, $roles) to check multiple roles -> Option A
  5. Quick Check:

    Variadic params + in_array = multiple roles check [OK]
Hint: Use ...$params and in_array() to check multiple middleware roles [OK]
Common Mistakes:
  • Treating multiple parameters as single string
  • Comparing string directly to array
  • Not using variadic parameters for multiple roles
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