Debug School

rakesh kumar
rakesh kumar

Posted on

Laravel - Request

  1. Retrieving the Request URI
  2. Retrieving Input

  3. Request Path, Host, & Method

  4. Request Headers

  5. Request IP Address

  6. Retrieving All Input Data

  7. Retrieving Input From The Query String

  8. Retrieving JSON Input Values

  9. Retrieving Stringable Input Values

  10. Retrieving Boolean Input Values

  11. Retrieving Date Input Values

  12. Retrieving A Portion Of The Input Data

  13. Determining If Input Is Present

  14. Merging Additional Input

  15. Old Input

  16. Cookies

Retrieving the Request URI
The “path” method is used to retrieve the requested URI. The is method is used to retrieve the requested URI which matches the particular pattern specified in the argument of the method. To get the full URL, we can use the url method.

Example
Step 1 − Execute the below command to create a new controller called UriController.

php artisan make:controller UriController –plain
Enter fullscreen mode Exit fullscreen mode

Step 2 − After successful execution of the URL, you will receive the following output −

Image description
Step 3 − After creating a controller, add the following code in that file.

app/Http/Controllers/UriController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class UriController extends Controller {

   public function index(Request $request) {
      // Usage of path method
      $path = $request->path();
      echo 'Path Method: '.$path;
      echo '<br>';

      // Usage of is method
      $pattern = $request->is('foo/*');
      echo 'is Method: '.$pattern;
      echo '<br>';

      // Usage of url method
      $url = $request->url();
      echo 'URL method: '.$url;
   }
}
Enter fullscreen mode Exit fullscreen mode

Image description

Step 4 − Add the following line in the app/Http/route.php file.

app/Http/route.php
Enter fullscreen mode Exit fullscreen mode

Route::get('/foo/bar','UriController@index');
Step 5 − Visit the following URL.

http://localhost:8000/foo/bar
Enter fullscreen mode Exit fullscreen mode

Step 6 − The output will appear as shown in the following image.

Image description
Retrieving Input
The input values can be easily retrieved in Laravel. No matter what method was used “get” or “post”, the Laravel method will retrieve input values for both the methods the same way. There are two ways we can retrieve the input values.

Using the input() method
Using the properties of Request instance
Using the input() method
The input() method takes one argument, the name of the field in form. For example, if the form contains username field then we can access it by the following way.

$name = $request->input('username');
Enter fullscreen mode Exit fullscreen mode

Using the properties of Request instance
Like the input() method, we can get the username property directly from the request instance.

$request->username
Enter fullscreen mode Exit fullscreen mode

Example
Observe the following example to understand more about Requests −

Step 1 − Create a Registration form, where user can register himself and store the form at resources/views/register.php

<html>

   <head>
      <title>Form Example</title>
   </head>

   <body>
      <form action = "/user/register" method = "post">
         <input type = "hidden" name = "_token" value = "<?php echo csrf_token() ?>">

         <table>
            <tr>
               <td>Name</td>
               <td><input type = "text" name = "name" /></td>
            </tr>
            <tr>
               <td>Username</td>
               <td><input type = "text" name = "username" /></td>
            </tr>
            <tr>
               <td>Password</td>
               <td><input type = "text" name = "password" /></td>
            </tr>
            <tr>
               <td colspan = "2" align = "center">
                  <input type = "submit" value = "Register" />
               </td>
            </tr>
         </table>

      </form>
   </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Step 2 − Execute the below command to create a UserRegistration controller.

php artisan make:controller UserRegistration --plain
Enter fullscreen mode Exit fullscreen mode

Step 3 − After successful execution of the above step, you will receive the following output −

Image description
** Step 4 − Copy the following code in**

app/Http/Controllers/UserRegistration.php controller.

app/Http/Controllers/UserRegistration.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class UserRegistration extends Controller {
   public function postRegister(Request $request) {
      //Retrieve the name input field
      $name = $request->input('name');
      echo 'Name: '.$name;
      echo '<br>';

      //Retrieve the username input field
      $username = $request->username;
      echo 'Username: '.$username;
      echo '<br>';

      //Retrieve the password input field
      $password = $request->password;
      echo 'Password: '.$password;
   }
}
Enter fullscreen mode Exit fullscreen mode

Step 5 − Add the following line in app/Http/routes.php file.


app/Http/routes.php

Route::get('/register',function() {
   return view('register');
});
Route::post('/user/register',array('uses'=>'UserRegistration@postRegister'));
Enter fullscreen mode Exit fullscreen mode

Step 6 − Visit the following URL and you will see the registration form as shown in the below figure. Type the registration details and click Register and you will see on the second page that we have retrieved and displayed the user registration details.

http://localhost:8000/register
Enter fullscreen mode Exit fullscreen mode

Step 7 − The output will look something like as shown in below the following images.
Image description

Request Path, Host, & Method
The Illuminate\Http\Request instance provides a variety of methods for examining the incoming HTTP request and extends the Symfony\Component\HttpFoundation\Request class. We will discuss a few of the most important methods below.

Retrieving The Request Path
The path method returns the request's path information. So, if the incoming request is targeted at http://example.com/foo/bar, the path method will return foo/bar:

$uri = $request->path();
Enter fullscreen mode Exit fullscreen mode

Inspecting The Request Path / Route
The is method allows you to verify that the incoming request path matches a given pattern. You may use the * character as a wildcard when utilizing this method:

if ($request->is('admin/*')) {
    //
}
Enter fullscreen mode Exit fullscreen mode

Using the routeIs method, you may determine if the incoming request has matched a named route:

if ($request->routeIs('admin.*')) {
    //
}

Enter fullscreen mode Exit fullscreen mode

Retrieving The Request URL
To retrieve the full URL for the incoming request you may use the url or fullUrl methods. The url method will return the URL without the query string, while the fullUrl method includes the query string:

$url = $request->url();

$urlWithQueryString = $request->fullUrl();
Enter fullscreen mode Exit fullscreen mode

If you would like to append query string data to the current URL, you may call the **fullUrlWithQuery **method. This method merges the given array of query string variables with the current query string:

$request->fullUrlWithQuery(['type' => 'phone']);
Enter fullscreen mode Exit fullscreen mode

Retrieving The Request Host
You may retrieve the "host" of the incoming request via the host, httpHost, and schemeAndHttpHost methods:

$request->host();
$request->httpHost();
$request->schemeAndHttpHost();
Enter fullscreen mode Exit fullscreen mode

Retrieving The Request Method
The method method will return the HTTP verb for the request. You may use the isMethod method to verify that the HTTP verb matches a given string:


$method = $request->method();

if ($request->isMethod('post')) {
    //
}
Enter fullscreen mode Exit fullscreen mode

Request Headers
You may retrieve a request header from the Illuminate\Http\Request instance using the header method. If the header is not present on the request, null will be returned. However, the header method accepts an optional second argument that will be returned if the header is not present on the request:

$value = $request->header('X-Header-Name');

$value = $request->header('X-Header-Name', 'default');
Enter fullscreen mode Exit fullscreen mode

The hasHeader method may be used to determine if the request contains a given header:

if ($request->hasHeader('X-Header-Name')) {
    //
}
Enter fullscreen mode Exit fullscreen mode

For convenience, the bearerToken method may be used to retrieve a bearer token from the Authorization header. If no such header is present, an empty string will be returned:

$token = $request->bearerToken();
Enter fullscreen mode Exit fullscreen mode

Request IP Address
The ip method may be used to retrieve the IP address of the client that made the request to your application:

$ipAddress = $request->ip();
Enter fullscreen mode Exit fullscreen mode

Retrieving All Input Data
You may retrieve all of the incoming request's input data as an array using the all method. This method may be used regardless of whether the incoming request is from an HTML form or is an XHR request:

$input = $request->all();
Enter fullscreen mode Exit fullscreen mode

Using the collect method, you may retrieve all of the incoming request's input data as a collection:

$input = $request->collect();
Enter fullscreen mode Exit fullscreen mode

The collect method also allows you to retrieve a subset of the incoming request input as a collection:

$request->collect('users')->each(function ($user) {
    // ...
});
Enter fullscreen mode Exit fullscreen mode

Retrieving An Input Value
Using a few simple methods, you may access all of the user input from your Illuminate\Http\Request instance without worrying about which HTTP verb was used for the request. Regardless of the HTTP verb, the input method may be used to retrieve user input:


$name = $request->input('name');
Enter fullscreen mode Exit fullscreen mode

You may pass a default value as the second argument to the input method. This value will be returned if the requested input value is not present on the request:

$name = $request->input('name', 'Sally');
Enter fullscreen mode Exit fullscreen mode

When working with forms that contain array inputs, use "dot" notation to access the arrays:

$name = $request->input('products.0.name');

$names = $request->input('products.*.name');
Enter fullscreen mode Exit fullscreen mode

You may call the input method without any arguments in order to retrieve all of the input values as an associative array:

$input = $request->input();
Enter fullscreen mode Exit fullscreen mode

Retrieving Input From The Query String
While the input method retrieves values from the entire request payload (including the query string), the query method will only retrieve values from the query string:

$name = $request->query('name');
Enter fullscreen mode Exit fullscreen mode

If the requested query string value data is not present, the second argument to this method will be returned:

$name = $request->query('name', 'Helen');
Enter fullscreen mode Exit fullscreen mode

You may call the query method without any arguments in order to retrieve all of the query string values as an associative array:

$query = $request->query();
Enter fullscreen mode Exit fullscreen mode

Retrieving JSON Input Values
When sending JSON requests to your application, you may access the JSON data via the input method as long as the Content-Type header of the request is properly set to application/json. You may even use "dot" syntax to retrieve values that are nested within JSON arrays / objects:

$name = $request->input('user.name');
Enter fullscreen mode Exit fullscreen mode

Retrieving Stringable Input Values
Instead of retrieving the request's input data as a primitive string, you may use the string method to retrieve the request data as an instance of Illuminate\Support\Stringable:

$name = $request->string('name')->trim();
Enter fullscreen mode Exit fullscreen mode

Retrieving Boolean Input Values
When dealing with HTML elements like checkboxes, your application may receive "truthy" values that are actually strings. For example, "true" or "on". For convenience, you may use the boolean method to retrieve these values as booleans. The boolean method returns true for 1, "1", true, "true", "on", and "yes". All other values will return false:

$archived = $request->boolean('archived');
Enter fullscreen mode Exit fullscreen mode

Retrieving Date Input Values
For convenience, input values containing dates / times may be retrieved as Carbon instances using the date method. If the request does not contain an input value with the given name, null will be returned:

$birthday = $request->date('birthday');
Enter fullscreen mode Exit fullscreen mode

The second and third arguments accepted by the date method may be used to specify the date's format and timezone, respectively:

$elapsed = $request->date('elapsed', '!H:i', 'Europe/Madrid');
Enter fullscreen mode Exit fullscreen mode

If the input value is present but has an invalid format, an InvalidArgumentException will be thrown; therefore, it is recommended that you validate the input before invoking the date method.

Retrieving Enum Input Values
Input values that correspond to PHP enums may also be retrieved from the request. If the request does not contain an input value with the given name or the enum does not have a backing value that matches the input value, null will be returned. The enum method accepts the name of the input value and the enum class as its first and second arguments:

use App\Enums\Status;

$status = $request->enum('status', Status::class);
Enter fullscreen mode Exit fullscreen mode

Retrieving Input Via Dynamic Properties
You may also access user input using dynamic properties on the Illuminate\Http\Request instance. For example, if one of your application's forms contains a name field, you may access the value of the field like so:

$name = $request->name;
Enter fullscreen mode Exit fullscreen mode

When using dynamic properties, Laravel will first look for the parameter's value in the request payload. If it is not present, Laravel will search for the field in the matched route's parameters.

Retrieving A Portion Of The Input Data
If you need to retrieve a subset of the input data, you may use the only and except methods. Both of these methods accept a single array or a dynamic list of arguments:

$input = $request->only(['username', 'password']);

$input = $request->only('username', 'password');

$input = $request->except(['credit_card']);

$input = $request->except('credit_card');
Enter fullscreen mode Exit fullscreen mode

The only method returns all of the key / value pairs that you request; however, it will not return key / value pairs that are not present on the request.

Determining If Input Is Present
You may use the has method to determine if a value is present on the request. The has method returns true if the value is present on the request:


if ($request->has('name')) {
    //
}
Enter fullscreen mode Exit fullscreen mode

When given an array, the has method will determine if all of the specified values are present:

if ($request->has(['name', 'email'])) {
    //
}
Enter fullscreen mode Exit fullscreen mode

The whenHas method will execute the given closure if a value is present on the request:

$request->whenHas('name', function ($input) {
    //
});
Enter fullscreen mode Exit fullscreen mode

A second closure may be passed to the whenHas method that will be executed if the specified value is not present on the request:

$request->whenHas('name', function ($input) {
    // The "name" value is present...
}, function () {
    // The "name" value is not present...
});
Enter fullscreen mode Exit fullscreen mode

The hasAny method returns true if any of the specified values are present:

if ($request->hasAny(['name', 'email'])) {
    //
}
Enter fullscreen mode Exit fullscreen mode

If you would like to determine if a value is present on the request and is not an empty string, you may use the filled method:

if ($request->filled('name')) {
    //
}
Enter fullscreen mode Exit fullscreen mode

The whenFilled method will execute the given closure if a value is present on the request and is not an empty string:

$request->whenFilled('name', function ($input) {
    //
});
Enter fullscreen mode Exit fullscreen mode

A second closure may be passed to the whenFilled method that will be executed if the specified value is not "filled":

$request->whenFilled('name', function ($input) {
    // The "name" value is filled...
}, function () {
    // The "name" value is not filled...
});
Enter fullscreen mode Exit fullscreen mode

To determine if a given key is absent from the request, you may use the missing method:

if ($request->missing('name')) {
    //
}
Enter fullscreen mode Exit fullscreen mode

Merging Additional Input
Sometimes you may need to manually merge additional input into the request's existing input data. To accomplish this, you may use the merge method:

$request->merge(['votes' => 0]);
Enter fullscreen mode Exit fullscreen mode

The mergeIfMissing method may be used to merge input into the request if the corresponding keys do not already exist within the request's input data:

$request->mergeIfMissing(['votes' => 0]);
Enter fullscreen mode Exit fullscreen mode

Old Input
Laravel allows you to keep input from one request during the next request. This feature is particularly useful for re-populating forms after detecting validation errors. However, if you are using Laravel's included validation features, it is possible that you will not need to manually use these session input flashing methods directly, as some of Laravel's built-in validation facilities will call them automatically.

Flashing Input To The Session
The flash method on the Illuminate\Http\Request class will flash the current input to the session so that it is available during the user's next request to the application:

$request->flash();

You may also use the flashOnly and flashExcept methods to flash a subset of the request data to the session. These methods are useful for keeping sensitive information such as passwords out of the session:

$request->flashOnly(['username', 'email']);

$request->flashExcept('password');
Enter fullscreen mode Exit fullscreen mode

Flashing Input Then Redirecting
Since you often will want to flash input to the session and then redirect to the previous page, you may easily chain input flashing onto a redirect using the withInput method:

return redirect('form')->withInput();

return redirect()->route('user.create')->withInput();

return redirect('form')->withInput(
    $request->except('password')
);
Enter fullscreen mode Exit fullscreen mode

Retrieving Old Input
To retrieve flashed input from the previous request, invoke the old method on an instance of Illuminate\Http\Request. The old method will pull the previously flashed input data from the session:

$username = $request->old('username');
Enter fullscreen mode Exit fullscreen mode

Laravel also provides a global old helper. If you are displaying old input within a Blade template, it is more convenient to use the old helper to repopulate the form. If no old input exists for the given field, null will be returned:

<input type="text" name="username" value="{{ old('username') }}">
Enter fullscreen mode Exit fullscreen mode

Cookies
Retrieving Cookies From Requests
All cookies created by the Laravel framework are encrypted and signed with an authentication code, meaning they will be considered invalid if they have been changed by the client. To retrieve a cookie value from the request, use the cookie method on an Illuminate\Http\Request instance:

$value = $request->cookie('name');
Enter fullscreen mode Exit fullscreen mode

Top comments (0)