In a request listener I get a Request where I need to check the presence of certain query parameter, and if it exists, redirect to a slightly changed URL:
So I check Request::query
and modify accordingly.
if ($request->query->has('foo')) {
$request->query->set('foo', 'bar');
}
if ($request->query->has('baz')) {
$request->query->remove('baz');
}
But after this I call:
$request->getUri()
$request->getRequestUri()
... and the returned URL still has the original values for foo
and baz
in the query string.
Can I get the modified URL directly from the request object?
Thanks, regards.
CodePudding user response:
One needs to call overrideGlobals()
.
From its docblock:
Overrides the PHP global variables according to this request instance.
if ($request->query->has('foo')) {
$request->query->set('foo', 'bar');
}
if ($request->query->has('baz')) {
$request->query->remove('baz');
}
$request->overrideGlobals();
$request->getUri();
Now it will print the correct URL.
CodePudding user response:
If you have a look inside Symfony code you might understand better what you're doing.
Here is the method set of the query
:
public function set(string $key, $value) { ... some verification $this->parameters[$key] = $value; }
It does change an array of parameters.
The methods getUri()
or getRequestUri()
on the other hand are method from the Request
and not the $request->query
and they do not care about $request->query->parameters
I don't exactly know what you're trying to do, but if you're trying to redirect to a given route with given parameters when you have given parameters you could try something like this in your controller action:
return new RedirectResponse($this->router->generate('your_route', $request->query->all());
Or building your own array of parameters rather than using $request->query->parameters
and then redirect to your route.