Pass Named Handler Arguments to Middleware in Laravel


April 24th, 2020


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:

            '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:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.