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

minjon's avatar
Level 15

How to remove a query string from an url?

I have the following url:

request()->fullUrlWithQuery(['status'=>'published', 'category'=>'sport'])
// '/users/1/articles?status=published&category=sport'

and would like to remove 'category' to get:

request()->fullUrlWithQuery(['status'=>'published'])
// /'users/1/articles?status=published'

Whatever solution I try, the fullUrlWithQuery() appears to remember the original query.

0 likes
8 replies
Nakov's avatar

Have you tried

request()->except('category');

?

bobbybouwmann's avatar

Yeah, it automatically merges with the previously selected query that was added to the URL. Another option is doing it yourself

return resource()->fullUrl() . '?' . Arr::query(['status' => 'published']);

This is still pretty clean ;)

bobbybouwmann's avatar

@nakov except returns an array of items that are added to the query of the URL. In this case that won't work because we generate the URL again.

1 like
minjon's avatar
Level 15

Thank you @bobbybouwmann for directing me, even though your solution doesn't work with me b/c my dynamic part is the query I want to remove from, not to leave in the url.

Fortunately, Arr::query() is exactly what I was missing to append a query to a named route with a parameter.:):):) I couldn't find that helper method in the Laravel docs.

I ended up with the following solution:

$oldQuery = request()->query(); // status=published&category=sport

$newQuery = Arr::except($oldQuery, ['category']);

$url = route('users.articles.index', [$user, Arr::query($newQuery)]) 
//users/{user}/articles?status=published
Nakov's avatar
Nakov
Best Answer
Level 73

@minjon and @bobbybouwmann now, I believe that what I've shown above will work in this case :)

$url = route('users.articles.index', [$user] + request()->except('category')); 

Will produce the same result :)

4 likes
minjon's avatar
Level 15

@nakov Thank you so much for taking time to share, I was really stuck. Works great, and allows us to remove as many queries as we want, including 'page', which is very tricky with the fullUrlWithQuery() method.:)

JLevy's avatar

request()->fullUrlWithQuery(['status'=>'published', 'category => NULL]) Will remove the NULLed parameter

1 like

Please or to participate in this conversation.