Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Retrieve request URL without specific query parameters in Laravel

September 24, 2021 ·

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 (and 8.1), 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-read 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.

👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!

Comments?