Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Retrieve request URL without specific query parameters in Laravel

When you have a request in hand and if the URL is having a query string with different parameters, the easiest way to get the entire URL with the query string is using the fullUrl() method like so.

$urlWithQueryString = $request->fullUrl();

// https://www.amitmerchant.com?search=Laravel&sort=asc

Now, if you want to append additional parameters in the existing URL query string, you can use the fullUrlWithQuery() like so.

$urlWithQueryString = $request->fullUrlWithQuery(['lang' => 'en']);

// https://www.amitmerchant.com?search=Laravel&sort=asc&lang=en

The new fullUrlWithoutQuery method

Now, recently with this PR, Laravel 8.x is coming with a method called fullUrlWithoutQuery() which does exactly opposite of the fullUrlWithQuery() method. i.e it removes the specified query string parameters from the request URL.

So, if we use the fullUrlWithoutQuery() the previous example, it would look like so.

$urlWithQueryString = $request->fullUrlWithoutQuery('sort');

// https://www.amitmerchant.com?search=Laravel&lang=en

As you can tell, since we specified the sort parameter in the fullUrlWithoutQuery method, it would return the URL with that parameter removed from the URL.

If you want multiple parameters to be removed, you can pass in the array of target parameters like so.

$urlWithQueryString = $request->fullUrlWithoutQuery(['sort', 'lang']);

// https://www.amitmerchant.com?search=Laravel
Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?