php - Generate URL in Symfony 5 with GET parameters

In Symfony 5, I would like to generate an URL partially based on GET paramaters already posted.
Let's assume that the URL posted is:
user/edit/5?foo=1&bar=1&baz=1&qux=1
I would like to generate in the controller withoutfoo
:
user/edit/5?bar=1&baz=1&qux=1
First, I removefoo
parameter :
$request->query->remove('foo');
If I didn't get theuser_id
in the URL as route parameter (5), I would use:
$this->generateUrl('user_edit', $request->query->all());
But this is not working becauseuser_id
is missing. So how can I generated such URL without rewriting all variables:
$this->generateUrl('user_edit', ['id' => $user->getId(), ???]);
I was thinking about PHP functionarray_merge()
but this seems to me more a trick than an elegant solution:
$this->generateUrl('user_edit', array_merge(
['id' => $user->getId()],
$request->query->all())
);
Answer
Solution:
There is nothing wrong in usingarray_merge()
. That's exactly what you want to accomplish. It's not a "trick", it's a language feature.
If you want a less verbose syntax, just use+
.
$this->generateUrl('user_edit', $request->query->all() + ['id' => $user->getId()]);
The end result is exactly the same for the above, and it's shorter.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: malformed utf-8 characters, possibly incorrectly encoded
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.