November 20, 2016 —John Koster
request($key = null, $default = null)
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.
The following example demonstrates how to retrieve an instance of Request
using the request
helper function:
1<?php2 3$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<?php 2 3// Get client IP address. 4request()->ip(); 5 6// Determine if request is secure. 7if (request()->secure()) { 8 // Request is secure. 9}10 11// Determine if request is the result12// of an AJAX call.13if (request()->ajax()) {14 // Request is XMLHTTPRequest.15}
The following example demonstrates how to retrieve user input using instance methods. The examples assume that name
exists in the user input array.
1<?php2 3// Get the user's name from input.4$name = request()->input('name');5 6// Get the user's name from input7// with a default value.8$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<?php 2 3// Get the user's name from input. 4$name = request()->input('name'); 5$name = request('name'); 6 7// Get the user's name from input 8// with a default value. 9$name = request()->input('name', 'John Doe');10$name = request('name', 'John Doe');
Using the request
helper function, we can access only a subset of the user's input data:
1<?php2 3// Get only the user's name.4$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<?php2 3// Retrieve a subset of the user's input data.4$inputSubset = request([5 'name',6 'email'7]);
∎
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.