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

DimitrisBor's avatar

Change route file depending on cookie

Hi,

We are in the middle of a redesign / rewrite and we want to deploy changes that are not visible in production. So we can see and test the new features in production by just putting a cookie in the browser. Building an entirely new project was rejected and changing the code in a branch and then merging it after months would be a nightmare of conflicts.

Wat we've tried: The first approach was adding laravel pennant and created a feature flag in the AppServiceProvider

public function boot(Request $request)
    {
        Feature::deactivate('new-site');

        if ($request->hasCookie('new')) {
            Feature::activate('new-site');
        }
    }

In the web.php we then check if the feature is on and load the appropriate routes. The feature flag comes correct in the web.php but when a route is loaded it is cached.

Then we added 2 route files. web.php and web-new.php And in the RouteServiceProvider added something like this

protected function mapWebRoutes()
    {
        Route::middleware('web')
            ->namespace($this->namespace)
            ->group(base_path(Feature::active('new-site') ? 'routes/web.php' : 'routes/web-new.php'));
    }

Cached again...

Then we created a middleware but again it didn't worked. I think we can't bypass this limitation unless i'm missing something. We don't want to cache the routes because it depends in the cookie each time, but i understand why it is the way it is.

Is there any other way to achieve what we want? I don't think its a good idea to check the feature in the controller but to load a different controller. That way we could keep only what we want and throw away junk. Also we want the old site to work until we flip the switch.

Thanks

0 likes
3 replies
jaguarundi's avatar
Level 2

I may be lost here. Why don't you run php artisan route:clear on the production server while you are testing. Then when you are finished, turn the cache back on php artisan route:cache

Snapey's avatar

how about middleware that prefixes the routes when the feature flag is set and then have both web.php and new-web.php loaded at the same time but your prefix sends to /new/newroute ?

DimitrisBor's avatar

@jaguarundi Thanks for that!

I wasn't aware that route:clear would clear and not cache the routes again until you tell it to. I thought it would clear and cache it again on the next request. So with route:clear it will not cache the RouteServiceProvider and the ->group(base_path(Feature::active('new-site') ? 'routes/web.php' : 'routes/web-new.php')); will be executed each time. It works!

@snapey i couldn't get it to work with the middleware prefix. Also it would have changed my urls and i would prefer them to be the same.

Thanks for your help!

1 like

Please or to participate in this conversation.