PHPackages                             timacdonald/has-parameters - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. timacdonald/has-parameters

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

timacdonald/has-parameters
==========================

A trait that allows you to pass arguments to Laravel middleware in a more PHP'ish way.

v1.5.2(11mo ago)228271.7k↓28.1%13[2 PRs](https://github.com/timacdonald/has-parameters/pulls)1MITPHPPHP ^8.1CI failing

Since Apr 15Pushed 11mo ago4 watchersCompare

[ Source](https://github.com/timacdonald/has-parameters)[ Packagist](https://packagist.org/packages/timacdonald/has-parameters)[ RSS](/packages/timacdonald-has-parameters/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (4)Versions (11)Used By (1)

[![Has Parameters: a Laravel package by Tim MacDonald](/art/header.png)](/art/header.png)

Has Parameters
==============

[](#has-parameters)

A trait for Laravel middleware that allows you to pass arguments in a more PHP'ish way, including as a key =&gt; value pair for named parameters, and as a list for variadic 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.

Read more about the why in my blog post [Rethinking Laravel's middleware argument API](https://timacdonald.me/rethinking-laravels-middleware-argument-api/)

Installation
------------

[](#installation)

You can install using [composer](https://getcomposer.org/):

```
composer require timacdonald/has-parameters

```

Basic usage
-----------

[](#basic-usage)

To get started with an example, I'm going to use a stripped back version of Laravel's `ThrottleRequests`. First up, add the `HasParameters` trait to your middleware.

```
class ThrottleRequests
{
    use HasParameters;

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

You can now pass arguments to this middleware using the static `with()` method, using the parameter name as the key.

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

You'll notice at first this is a little more verbose, but I think you'll enjoy the complete feature set after reading these docs and taking it for a spin.

Middleware::with()
------------------

[](#middlewarewith)

The static `with()` method allows you to easily see which values represent what when declaring your middleware, instead of just declaring a comma seperate list of values. The order of the keys does not matter. The trait will pair up the keys to the parameter names in the `handle()` method.

```
// before...
Route::stuff()
    ->middleware([
        'throttle:10,1' // what does 10 or 1 stand for here?
    ]);

// after...
Route::stuff()
    ->middleware([
        ThrottleRequests::with([
            'decayMinutes' => 1,
            'maxAttempts' => 10,
        ]),
    ]);
```

### Skipping parameters

[](#skipping-parameters)

If any parameters in the `handle` method have a default value, you do not need to pass them through - unless you are changing their value. As an example, if you'd like to only specify a prefix for the `ThrottleRequests` middleware, but keep the `$decayMinutes` and `$maxAttempts` as their default values, you can do the following...

```
Route::stuff()
    ->middleware([
        ThrottleRequests::with([
            'prefix' => 'admins',
        ]),
    ]);
```

As we saw previously in the handle method, the default values of `$decayMinutes` is `1` and `$maxAttempts` is `60`. The middleware will receive those values for those parameters, but will now receive `"admins"` for the `$prefix`.

### Arrays for variadic parameters

[](#arrays-for-variadic-parameters)

When your middleware ends in a variadic paramater, you can pass an array of values for the variadic parameter key. Take a look at the following `handle()` method.

```
public function handle(Request $request, Closure $next, string $ability, string ...$models)
```

Here is how we can pass a list of values to the variadic `$models` parameter...

```
Route::stuff()
    ->middleware([
        Authorize::with([
            'ability' => PostVideoPolicy::UPDATE,
            'models' => [Post::class, Video::class],
        ]),
    ]);
```

### Parameter aliases

[](#parameter-aliases)

Some middleware will have different behaviour based on the type of values passed through to a specific parameter. As an example, Laravel's `ThrottleRequests` middleware allows you to pass the name of a rate limiter to the `$maxAttempts` parameter, instead of a numeric value, in order to utilise that named limiter on the endpoint.

```
// a named rate limiter...

RateLimiter::for('api', function (Request $request) {
    return Limit::perMinute(60)->by(optional($request->user())->id ?: $request->ip());
});

// using the rate limiter WITHOUT an alias...

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

In this kind of scenario, it is nice to be able to alias the `$maxAttempts` parameter name to something more readable.

```
Route::stuff()
    ->middleware([
        ThrottleRequests::with([
            'limiter' => 'api',
        ]),
    ]);
```

To achieve this, you can setup a parameter alias map in your middleware...

```
class ThrottleRequests
{
    use HasParameters;

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

    protected static function parameterAliasMap(): array
    {
        return [
            'limiter' => 'maxAttempts',
            // 'alias' => 'parameter',
        ];
    }
}
```

### Validation

[](#validation)

These validations occur whenever the routes file is loaded or compiled, not just when you hit a route that contains the declaration.

#### Unexpected parameter

[](#unexpected-parameter)

Ensures that you do not declare any keys that do not exist as parameter variables in the `handle()` method. This helps make sure you don't mis-type a parameter name.

#### Required parameters

[](#required-parameters)

Ensures all required parameters (those without default values) have been provided.

#### Aliases

[](#aliases)

- Ensures all aliases specified reference an existing parameter.
- Provided aliases don't reference the same parameter.
- An original parameter key and an alias have not both been provided.

Middleware::in()
----------------

[](#middlewarein)

The static `in()` method very much reflects and works the same as the existing concatination API. It accepts a list of values, i.e. a non-associative array. You should use this method if your `handle()` method is a single variadic parameter, i.e. expecting a single list of values, as shown in the following middleware handle method... .

```
public function handle(Request $request, Closure $next, string ...$states)
{
    //
}
```

You can pass through a list of "states" to the middleware like so...

```
Route::stuff()
    ->middleware([
        EnsurePostState::in([PostState::DRAFT, PostState::UNDER_REVIEW]),
    ]);
```

### Validation

[](#validation-1)

#### Required parameters

[](#required-parameters-1)

Just like the `with()` method, the `in()` method will validate that you have passed enough values through to cover all the required parameters. Because variadic parameters do not require any values to be passed through, you only really rub up against this when you should probably be using the `with()` method.

Value transformation
--------------------

[](#value-transformation)

You should keep in mind that everything will still be cast to a string. Although you are passing in, for example, integers, the middleware itself will *always* receive a string. This is how Laravel works under-the-hood to implement route caching.

One thing to note is the `false` is actually cast to the string `"0"` to keep some consistency with casting `true` to a string, which results in the string `"1"`.

Typing values
-------------

[](#typing-values)

It is possible to provide stronge type information by utilising docblocks on your middleware class. Here is an example of how you could create a strongly typed middleware:

```
/**
 * @method static string with(array{
 *     maxAttempts?: int,
 *     decayMinutes?: float|int,
 *     prefix?: string,
 * }|'admin' $arguments)
 */
class ThrottleMiddleware
{
    use HasParameters;

    // ...
}
```

You will then receive autocomplete and diagnostics from your language server:

```
ThrottleMiddleware::with('admin');
// ✅

ThrottleMiddleware::with(['decayMinutes' => 10]);
// ✅

ThrottleMiddleware::with('foo');
// ❌ fails because 'foo' is not in the allowed string values

ThrottleMiddleware::with(['maxAttempts' => 'ten']);
// ❌ fails because `maxAttempts` must be an int
```

Checkout the example in the [PHPStan playground](https://phpstan.org/r/8c0ba5d8-a730-4fd9-9af8-bcec33d3b043).

Credits
-------

[](#credits)

- [Tim MacDonald](https://github.com/timacdonald)
- [All Contributors](../../contributors)

And a special (vegi) thanks to [Caneco](https://twitter.com/caneco) for the logo ✨

Thanksware
----------

[](#thanksware)

You are free to use this package, but I ask that you reach out to someone (not me) who has previously, or is currently, maintaining or contributing to an open source library you are using in your project and thank them for their work. Consider your entire tech stack: packages, frameworks, languages, databases, operating systems, frontend, backend, etc.

###  Health Score

53

—

FairBetter than 97% of packages

Maintenance50

Moderate activity, may be stable

Popularity52

Moderate usage in the ecosystem

Community24

Small or concentrated contributor base

Maturity71

Established project with proven stability

 Bus Factor1

Top contributor holds 70.4% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~207 days

Recently: every ~299 days

Total

10

Last Release

357d ago

PHP version history (3 changes)v1.0.0PHP ^7.1

v1.2.0PHP ^7.1 || ^8.0

v1.4.0PHP ^8.1

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/24803032?v=4)[Tim MacDonald](/maintainers/timacdonald)[@timacdonald](https://github.com/timacdonald)

---

Top Contributors

[![timacdonald](https://avatars.githubusercontent.com/u/24803032?v=4)](https://github.com/timacdonald "timacdonald (69 commits)")[![szainmehdi](https://avatars.githubusercontent.com/u/379169?v=4)](https://github.com/szainmehdi "szainmehdi (19 commits)")[![dependabot-preview[bot]](https://avatars.githubusercontent.com/in/2141?v=4)](https://github.com/dependabot-preview[bot] "dependabot-preview[bot] (3 commits)")[![laravel-shift](https://avatars.githubusercontent.com/u/15991828?v=4)](https://github.com/laravel-shift "laravel-shift (2 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (2 commits)")[![patrickomeara](https://avatars.githubusercontent.com/u/571773?v=4)](https://github.com/patrickomeara "patrickomeara (1 commits)")[![bpotmalnik](https://avatars.githubusercontent.com/u/20015942?v=4)](https://github.com/bpotmalnik "bpotmalnik (1 commits)")[![caneco](https://avatars.githubusercontent.com/u/502041?v=4)](https://github.com/caneco "caneco (1 commits)")

---

Tags

hacktoberfesthelperlaravelmiddlewarephptraitmiddlewarelaravelparametersarguments

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/timacdonald-has-parameters/health.svg)

```
[![Health](https://phpackages.com/badges/timacdonald-has-parameters/health.svg)](https://phpackages.com/packages/timacdonald-has-parameters)
```

###  Alternatives

[yajra/laravel-datatables-oracle

jQuery DataTables API for Laravel

4.9k33.8M339](/packages/yajra-laravel-datatables-oracle)[watson/active

Laravel helper for recognising the current route, controller and action

3253.6M14](/packages/watson-active)[laragear/preload

Effortlessly make a Preload script for your Laravel application.

119363.5k](/packages/laragear-preload)[glhd/conveyor-belt

14797.0k](/packages/glhd-conveyor-belt)[dragon-code/pretty-routes

Pretty Routes for Laravel

10058.7k4](/packages/dragon-code-pretty-routes)[erlandmuchasaj/laravel-gzip

Gzip your responses.

40129.3k2](/packages/erlandmuchasaj-laravel-gzip)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
