Laravel 5: Accessing HTTP Request Details With request

April 14, 2018 —John Koster

The request helper function is a useful helper function that can be used to either retrieve an instance of "Illuminate\Http\Request' or retrieve an item from the user's input. To retrieve an instance of Request, call the request method without supplying any arguments. To retrieve an input value, supply at least the $key argument.

#Signature

The signature of the request function is:

1function request(
2 $key = null,
3 $default = null
4);

#Example Use

The following example demonstrates how to retrieve an instance of Request using the request helper function:

1$requestInstance = request();

Since we have access to an instance of Request, we also have access to all of the instance methods available on Request:

1// Get client IP address.
2request()->ip();
3 
4// Determine if request is secure.
5if (request()->secure()) {
6 // Request is secure.
7}
8 
9// Determine if request is the result
10// of an AJAX call.
11if (request()->ajax()) {
12 // Request is XMLHTTPRequest.
13}

The following example demonstrates how to retrieve user input using instance methods. The examples assume that name exists in the user input array.

1// Get the user's name from input.
2$name = request()->input('name');
3 
4// Get the user's name from input
5// with a default value.
6$name = request()->input('name', 'John Doe');

The request helper function can also be used as a shortcut to the Request::input instance method. To use the request function supply at least the $key to retrieve from user input (and an optional $default value that will be returned if no user input exists for the given $key). The following examples are identical in their end result:

1// Get the user's name from input.
2$name = request()->input('name');
3$name = request('name');
4 
5// Get the user's name from input
6// with a default value.
7$name = request()->input('name', 'John Doe');
8$name = request('name', 'John Doe');

Using the request helper function, we can access only a subset of the user's input data:

1// Get only the user's name.
2$name = request()->only('name');

Receiving a subset of data can also be accomplished using the shorthand syntax introduced in Laravel 5.3. To take advantage of this shorthand syntax, simply supply an array as the only argument to the request helper function:

1// Retrieve a subset of the user's input data.
2$inputSubset = request([
3 'name',
4 'email'
5 ]);

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.