Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

filipgerat's avatar

Middleware handle method doesn't have typed parameter

Hello, is there any reason why the handle method has this signature public function handle($request, Closure $next, ...$guards) instead of public function handle(Request $request, Closure $next, ...$guards) ?

0 likes
1 reply
benjamincrozat's avatar

I noticed in Laravel that type hints are used only when necessary. You're free to do whatever you want with your code though.

public function handle($request, Closure $next, ...$guards)

$request is not resolved from the container, no need to type hint. But $next absolutely have to be a Closure.

Let's say you have a controller with an update() method:

public function update(Request $request, $id)

$request is resolved from the container thanks to the type hint. But do we need to type hint $id? I wouldn't. It takes less time to refactor when you don't have to update your type hints everywhere. $id could be a int, but it could change to string if I decide to use UUIDs some day. If your code is well tested, type hinting like crazy won't make it safer.

But like everything in life, nothing is either black or white. Using array type hint (or Closure in middlewares for example) is very useful. Without type hint, you have to check your variable before doing anything:

function do_something($value) {
    if (!is_array($value)) {
        throw Exception('...');
    }

    //
}

But with a type hint, you're guaranteed to have an array:

function do_something(array $value) {
    //
}

Please or to participate in this conversation.