Manipulate URLs with the request() method in Laravel

Consider that we have the follow URL in our address bar:

https://www.domain.tld/path/to/something?query=data&anotherQuery=

 

Get the current URL without query string

request()->url();

// https://www.domain.tld/path/to/something

NOTE: The url()->current() function give the same results.

Get the current URL (including the query string)

request()->fullUrl();

// https://www.domain.tld/path/to/something?query=data&anotherQuery=

Get the current URL’s path (as String)

request()->path();

// path/to/something

request()->getPathInfo();

// /path/to/something

Get the current URL’s path (as Array)

request()->segments();

/*
Array
(
    [0] => path
    [1] => to
    [2] => something
)
*/

request()->segments(1);

// path

Get the current domain (including the protocol)

request()->root();

// https://www.domain.tld

Get the query string (as String)

request()->getQueryString();

// query=data&anotherQuery=

Get the query string (as Array)

request()->query();

/*
Array
(
    [query] => data
    [anotherQuery] => 
)
*/

request()->query('query');

// data

NOTE: The request()->get('query') function give the same results.

Check if a key exists in the query string (even it is empty)

request()->has('anotherQuery');

// true

Check if a query string’s key is filled

request()->filled('anotherQuery');

// false

 

The codes bellow has been tested on Laravel 7.x