Kirill42
(Kirill)
January 14, 2026, 12:35pm
1
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?
samdark
(Alexander Makarov)
February 2, 2026, 10:43am
2
Because to prepend it you have to have the action to prepend to.
samdark
(Alexander Makarov)
February 2, 2026, 11:10am
3
But thinking more about it, we can probably remove this check…
1 Like
Kirill42
(Kirill)
February 2, 2026, 11:49am
4
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'])