Pass Named Handler Arguments to Middleware in Laravel

Pass Named Handler Arguments to Middleware in Laravel

Has Parameters is a Laravel package by Tim MacDonald to “pass arguments [to middleware] in a more PHP’ish way.”

Here’s an example of the primary usage as found in the project’s readme:

First, the following is a simplified example of what Laravel’s ThrottleRequests middleware might look like:

class ThrottleRequests
{
    use HasParameters;

    public function handle($request, Closure $next, $maxAttempts = 60, $decayMinutes = 1, $prefix = '')
    {
        //
    }
}

Then you could configure the middleware in a route like so:

Route::stuff()
    ->middleware([
        ThrottleRequests::with([
            'maxAttempts' => 120,
        ]),
    ]);

As you can see from the example, this package’s with() method found in the HasParameters trait will take care of working with parameters that have default values.

The readme outlines additional benefits of using this package with your app’s middleware:

[Has Parameters] improves static analysis / IDE support, allows you to specify arguments by referencing the parameter name, enables skipping optional parameters (which fallback to their default value), and adds some validation, so you don’t forget any required parameters by accident.

Learn More

Tim wrote an article (Rethinking Laravel’s middleware argument API) that details out the background behind this package and walks you through his thought process of how he arrived at this package.

You can learn more about this package, get full installation instructions, and view the source code on GitHub at timacdonald/has-parameters.

Filed in: News

Newsletter

Join 31,000+ others and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

Senior Laravel Developer
Remote
FPV Exchange
Senior Full-Stack Developer
Remote, USA Only
Givebutter
Senior PHP Developer
Cary, NC
INE
Backend PHP Developer
Hamburg
ABOUT YOU GmbH
Engineering Director
Vancouver or remote (EST/PST preferred)
Engine Digital