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

cosminc's avatar

Persisting query parameter across links on a given website

Hi everybody,

I'm trying to find the best solution for the following task - let's say a user accesses my website using a token in the url, something along the lines of http://www.example.com/?token=12345. What I would like to do next is to persist that token query parameter on any links from the website that the user might visit. The entry point can be any link available on the website.

If, for example, the entry point is http://www.example.com/?token=12345, if the user then clicks on the "About us" link, the url should become http://www.example.com/about-us/?token=12345

I'm feeling that this can be achieved with a middleware, but I don't know how exactly :)

Any help is appreciated.

Thanks.

0 likes
6 replies
MichalOravec's avatar

@cosminc Create your custom helper for named routes

if (! function_exists('query_route')) {
    function query_route($name, $parameters = [], $absolute = true)
    {
        return route($name, $parameters + request()->query(), $absolute);
    }
}

So instead of

{{ route('your-route') }}

You will use

{{ query_route('your-route') }}
1 like
cosminc's avatar

Tried your approach, @michaloravec, but this piece of code $parameters + request()->query() throws an "Unsupported operand types" exception. It looks like $parameters isn't an array.

MichalOravec's avatar

@cosminc So try array_merge

if (! function_exists('query_route')) {
    function query_route($name, $parameters = [], $absolute = true)
    {
	$parameters = Arr::wrap($parameters);

        return route($name, array_merge($parameters, request()->query()), $absolute);
    }
}

If you have routes like

route('something', $variable);

It has to be like

query_route('something', [$variable]);
1 like
cosminc's avatar

Yes, array_merge() was the first thing I tried, but it failed. Using [$variable] did the trick. Thank you.

Please or to participate in this conversation.