HTTP Requests

Accessing The Request

To obtain an instance of the current HTTP request via dependency injection, you should type-hint the Illuminate\Http\Request class on your controller method. The incoming request instance will automatically be injected by the service container:

  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Http\Request;
  4. class UserController extends Controller
  5. {
  6. /**
  7. * Store a new user.
  8. *
  9. * @param Request $request
  10. * @return Response
  11. */
  12. public function store(Request $request)
  13. {
  14. $name = $request->input('name');
  15. //
  16. }
  17. }

Dependency Injection & Route Parameters

If your controller method is also expecting input from a route parameter you should list your route parameters after your other dependencies. For example, if your route is defined like so:

  1. Route::put('user/{id}', '[email protected]');

You may still type-hint the Illuminate\Http\Request and access your route parameter id by defining your controller method as follows:

  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Http\Request;
  4. class UserController extends Controller
  5. {
  6. /**
  7. * Update the specified user.
  8. *
  9. * @param Request $request
  10. * @param string $id
  11. * @return Response
  12. */
  13. public function update(Request $request, $id)
  14. {
  15. //
  16. }
  17. }

Accessing The Request Via Route Closures

You may also type-hint the Illuminate\Http\Request class on a route Closure. The service container will automatically inject the incoming request into the Closure when it is executed:

  1. use Illuminate\Http\Request;
  2. Route::get('/', function (Request $request) {
  3. //
  4. });

Request Path & Method

The Illuminate\Http\Request instance provides a variety of methods for examining the HTTP request for your application 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://domain.com/foo/bar, the path method will return foo/bar:

  1. $uri = $request->path();

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:

  1. if ($request->is('admin/*')) {
  2. //
  3. }

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:

  1. // Without Query String...
  2. $url = $request->url();
  3. // With Query String...
  4. $url = $request->fullUrl();

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:

  1. $method = $request->method();
  2. if ($request->isMethod('post')) {
  3. //
  4. }

PSR-7 Requests

The PSR-7 standard specifies interfaces for HTTP messages, including requests and responses. If you would like to obtain an instance of a PSR-7 request instead of a Laravel request, you will first need to install a few libraries. Laravel uses the Symfony HTTP Message Bridge component to convert typical Laravel requests and responses into PSR-7 compatible implementations:

  1. composer require symfony/psr-http-message-bridge
  2. composer require zendframework/zend-diactoros

Once you have installed these libraries, you may obtain a PSR-7 request by type-hinting the request interface on your route Closure or controller method:

  1. use Psr\Http\Message\ServerRequestInterface;
  2. Route::get('/', function (ServerRequestInterface $request) {
  3. //
  4. });

{tip} If you return a PSR-7 response instance from a route or controller, it will automatically be converted back to a Laravel response instance and be displayed by the framework.

Input Trimming & Normalization

By default, Laravel includes the TrimStrings and ConvertEmptyStringsToNull middleware in your application's global middleware stack. These middleware are listed in the stack by the App\Http\Kernel class. These middleware will automatically trim all incoming string fields on the request, as well as convert any empty string fields to null. This allows you to not have to worry about these normalization concerns in your routes and controllers.

If you would like to disable this behavior, you may remove the two middleware from your application's middleware stack by removing them from the $middleware property of your App\Http\Kernel class.

Retrieving Input

Retrieving All Input Data

You may also retrieve all of the input data as an array using the all method:

  1. $input = $request->all();

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:

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

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:

  1. $name = $request->input('name', 'Sally');

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

  1. $name = $request->input('products.0.name');
  2. $names = $request->input('products.*.name');

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:

  1. $name = $request->name;

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 route parameters.

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 dig into JSON arrays:

  1. $name = $request->input('user.name');

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:

  1. $input = $request->only(['username', 'password']);
  2. $input = $request->only('username', 'password');
  3. $input = $request->except(['credit_card']);
  4. $input = $request->except('credit_card');

The only method returns all of the key / value pairs that you request, even if the key is not present on the incoming request. When the key is not present on the request, the value will be null. If you would like to retrieve a portion of input data that is actually present on the request, you may use the intersect method:

  1. $input = $request->intersect(['username', 'password']);

Determining If An Input Value Is Present

You should use the has method to determine if a value is present on the request. The has method returns true if the value is present and is not an empty string:

  1. if ($request->has('name')) {
  2. //
  3. }

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

  1. if ($request->has(['name', 'email'])) {
  2. //
  3. }

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 unlikely you will need to manually use these methods, 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:

  1. $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:

  1. $request->flashOnly(['username', 'email']);
  2. $request->flashExcept('password');

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:

  1. return redirect('form')->withInput();
  2. return redirect('form')->withInput(
  3. $request->except('password')
  4. );

Retrieving Old Input

To retrieve flashed input from the previous request, use the old method on the Request instance. The old method will pull the previously flashed input data from the session:

  1. $username = $request->old('username');

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. If no old input exists for the given field, null will be returned:

  1. <input type="text" name="username" value="{{ old('username') }}">

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 a Illuminate\Http\Request instance:

  1. $value = $request->cookie('name');

Attaching Cookies To Responses

You may attach a cookie to an outgoing Illuminate\Http\Response instance using the cookie method. You should pass the name, value, and number of minutes the cookie should be considered valid to this method:

  1. return response('Hello World')->cookie(
  2. 'name', 'value', $minutes
  3. );

The cookie method also accepts a few more arguments which are used less frequently. Generally, these arguments have the same purpose and meaning as the arguments that would be given to PHP's native setcookie method:

  1. return response('Hello World')->cookie(
  2. 'name', 'value', $minutes, $path, $domain, $secure, $httpOnly
  3. );

If you would like to generate a Symfony\Component\HttpFoundation\Cookie instance that can be given to a response instance at a later time, you may use the global cookie helper. This cookie will not be sent back to the client unless it is attached to a response instance:

  1. $cookie = cookie('name', 'value', $minutes);
  2. return response('Hello World')->cookie($cookie);

Files

Retrieving Uploaded Files

You may access uploaded files from a Illuminate\Http\Request instance using the file method or using dynamic properties. The file method returns an instance of the Illuminate\Http\UploadedFile class, which extends the PHP SplFileInfo class and provides a variety of methods for interacting with the file:

  1. $file = $request->file('photo');
  2. $file = $request->photo;

You may determine if a file is present on the request using the hasFile method:

  1. if ($request->hasFile('photo')) {
  2. //
  3. }

Validating Successful Uploads

In addition to checking if the file is present, you may verify that there were no problems uploading the file via the isValid method:

  1. if ($request->file('photo')->isValid()) {
  2. //
  3. }

File Paths & Extensions

The UploadedFile class also contains methods for accessing the file's fully-qualified path and its extension. The extension method will attempt to guess the file's extension based on its contents. This extension may be different from the extension that was supplied by the client:

  1. $path = $request->photo->path();
  2. $extension = $request->photo->extension();

Other File Methods

There are a variety of other methods available on UploadedFile instances. Check out the API documentation for the class for more information regarding these methods.

Storing Uploaded Files

To store an uploaded file, you will typically use one of your configured filesystems. The UploadedFile class has a store method which will move an uploaded file to one of your disks, which may be a location on your local filesystem or even a cloud storage location like Amazon S3.

The store method accepts the path where the file should be stored relative to the filesystem's configured root directory. This path should not contain a file name, since a unique ID will automatically be generated to serve as the file name.

The store method also accepts an optional second argument for the name of the disk that should be used to store the file. The method will return the path of the file relative to the disk's root:

  1. $path = $request->photo->store('images');
  2. $path = $request->photo->store('images', 's3');

If you do not want a file name to be automatically generated, you may use the storeAs method, which accepts the path, file name, and disk name as its arguments:

  1. $path = $request->photo->storeAs('images', 'filename.jpg');
  2. $path = $request->photo->storeAs('images', 'filename.jpg', 's3');