The requirement for the Yiisoft\Router\Route::prependMiddleware method needs to be explained

The Yiisoft\Router\Route::prependMiddleware() method has a requirement that the prependMiddleware() method cannot be used before the action().
Here is an example of using the prependMiddleware() method:

Route::get('/info')
    ->action([SiteController::class, 'info'])
    ->name('site/info')
    ->prependMiddleware(MyMiddleware::class)

However, despite this requirement, the middleware is executed before the action.
I wonder, then, why prependMiddleware() method contains this requirement?

Because to prepend it you have to have the action to prepend to.

But thinking more about it, we can probably remove this check…

1 Like

With the middleware method:

Route::get('/info')
    ->middleware(MyMiddleware1::class)
    ->middleware(MyMiddleware2::class)
    ->action([SiteController::class, 'info'])
    ->name('site/info')

The execution order is: MyMiddleware1 → MyMiddleware2 → Info action

With the prependMiddleware method:

Route::get('/info')
    ->middleware(MyMiddleware1::class)
    ->action([SiteController::class, 'info'])
    ->name('site/info')
    ->prependMiddleware(MyMiddleware2::class)

The execution order is: MyMiddleware2 → MyMiddleware1 → Info action

The prependMiddleware method only changes the execution order within a set of middlewares, not between an action and a middleware.
So why can’t we get the same behavior with a code like this:

Route::get('/info')
    ->middleware(MyMiddleware1::class)
    ->prependMiddleware(MyMiddleware2::class)
    ->action([SiteController::class, 'info'])
1 Like