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

boneill81's avatar

Pass variable from route to middleware??

I have two middleware classes set-up in my application to cache the output of my views. Its all working a treat but I wanted to know how would you go about passing a custom variable with the route to the middleware.

My thought process is this, at present I have the middlewares listed in my $routeMiddleware in kernel.php.

However rather than call ->middleware() on each route, I would prefer to activate the middleware for all routes in $middlewareGroups and then just pass a custom "noCache" variable on the routes that I do not want cached. I can then include a check for this in the middleware.

So something like the following.

Route::get('contact-us', ['as' => 'contactUs', 'uses' => 'PagesController@contactUs'])->with('noCache' => true);

Is this a possibility in Laravel(I'm on 5.2).

Thanks.

0 likes
2 replies
martinbean's avatar
Level 80

@boneill81 You can’t pass arbitrary variables to middleware like this, as far as I know. If you want to add headers to “cache-bust” then just create a middleware class for that:

Route::group(['middleware' => 'nocache'], function () {
    Route::get('contact-us', 'PagesController@contactUs')->name('contactUs');
});
2 likes

Please or to participate in this conversation.