mvww11's avatar

Add query string to current url

Hello, folks!

I want to add a query string to the current URL when clicking on a button or radio button.

For example: /subjects becomes /subjects?popular and /subjects?new becomes /subjects?new&popular

Thanks!

0 likes
6 replies
edoc's avatar

Can you try this?

<a href="{{ url('subjects', 'popular')}}">
<a href="{{ url('subjects', ['popular', 'new'])}}">
mvww11's avatar

@edoc thanks for the reply!

It seems to me that your code assumes that I already know the query strings that are present in the URL. But I do not so!

In fact, I don't even know If there is some query string present in the URL.

Is there something that Im missing?

1 like
mvww11's avatar
mvww11
OP
Best Answer
Level 2

Found a way, folks!

//Retrieve current query strings:
$currentQueries = $request->query();

//Declare new queries you want to append to string:
$newQueries = ['foo' => 'bar', 'popular'];

//Merge together current and new query strings:
$allQueries = array_merge($currentQueries, $newQueries);

//Generate the URL with all the queries:
$request->fullUrlWithQuery($allQueries);
9 likes
luchaos's avatar

Thanks @mvww11! That was a very valuable hint.

Fwiw, it looks like the additional query parameters do not have to be merged manually to get the same result:

$request->fullUrlWithQuery(['foo' => 'bar', 'popular']);

Worked for me, added the parameters to the existing ones. (Running Laravel 5.7)

Which is especially nice for usage within blade templates in a concise manner. Adding an additional country filter to the existing ones there to find users in the same country:

<a href="{{ request()->fullUrlWithQuery(['country' => $user->country_code]) }}">
    All users in {{ trans('countries.'.$user->country_code) }}
</a>
7 likes

Please or to participate in this conversation.