Skip to content

Commit

Permalink
working on request documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
taylorotwell committed Jul 12, 2016
1 parent 63de839 commit 68e344e
Showing 1 changed file with 98 additions and 63 deletions.
161 changes: 98 additions & 63 deletions requests.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# HTTP Requests

- [Accessing The Request](#accessing-the-request)
- [Basic Request Information](#basic-request-information)
- [Request Path & Method](#request-path-and-method)
- [PSR-7 Requests](#psr7-requests)
- [Retrieving Input](#retrieving-input)
- [Old Input](#old-input)
Expand All @@ -11,7 +11,7 @@
<a name="accessing-the-request"></a>
## 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 constructor or method. The current request instance will automatically be injected by the [service container](/docs/{{version}}/container):
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](/docs/{{version}}/container):

<?php

Expand All @@ -35,11 +35,13 @@ To obtain an instance of the current HTTP request via dependency injection, you
}
}

If your controller method is also expecting input from a route parameter, simply list your route arguments after your other dependencies. For example, if your route is defined like so:
#### 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:

Route::put('user/{id}', 'UserController@update');

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

<?php

Expand All @@ -62,38 +64,46 @@ You may still type-hint the `Illuminate\Http\Request` and access your route para
}
}

<a name="basic-request-information"></a>
### Basic Request Information
#### 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:

use Illuminate\Http\Request;

Route::get('/', function (Request $request) {
//
});

<a name="request-path-and-method"></a>
### 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. Here are a few more of the useful methods available on this class:
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 URI
#### Retrieving The Request Path

The `path` method returns the request's URI. So, if the incoming request is targeted at `http://domain.com/foo/bar`, the `path` method will return `foo/bar`:
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`:

$uri = $request->path();

The `is` method allows you to verify that the incoming request URI matches a given pattern. You may use the `*` character as a wildcard when utilizing this method:
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/*')) {
//
}

To get the full URL, not just the path info, you may use the `url` or `fullUrl` methods on the request instance:
#### 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:

// Without Query String...
$url = $request->url();

// With Query String...
$url = $request->fullUrl();

You may also get the full URL and append query parameters. For example, if the request is targeted at `http://domain.com/foo`, the following method will return `http://domain.com/foo?bar=baz`:

$url = $request->fullUrlWithQuery(['bar' => 'baz']);

#### Retrieving The Request Method

The `method` method will return the HTTP verb for the request. You may also use the `isMethod` method to verify that the HTTP verb matches a given string:
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();

Expand All @@ -104,64 +114,63 @@ The `method` method will return the HTTP verb for the request. You may also use
<a name="psr7-requests"></a>
### 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, 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:
The [PSR-7 standard](http://www.php-fig.org/psr/psr-7/) 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:

composer require symfony/psr-http-message-bridge

composer require zendframework/zend-diactoros

Once you have installed these libraries, you may obtain a PSR-7 request by simply type-hinting the request type on your route or controller:
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:

use Psr\Http\Message\ServerRequestInterface;

Route::get('/', function (ServerRequestInterface $request) {
//
});

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.
> {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.
<a name="retrieving-input"></a>
## Retrieving Input

#### Retrieving All Input Data

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

$input = $request->all();

#### Retrieving An Input Value

Using a few simple methods, you may access all user input from your `Illuminate\Http\Request` instance. You do not need to worry about the HTTP verb used for the request, as input is accessed in the same way for all verbs:
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');

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');

When working on forms with array inputs, you may use "dot" notation to access the arrays:
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');

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

$name = $request->input('user.name');
#### Retrieving Input Via Dynamic Properties

#### Determining If An Input Value Is Present
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:

To determine if a value is present on the request, you may use the `has` method. The `has` method returns `true` if the value is present **and** is not an empty string:
$name = $request->name;

if ($request->has('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 All Input Data
#### Retrieving JSON Input Values

You may also retrieve all of the input data as an `array` using the `all` method:
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:

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

#### Retrieving A Portion Of The Input Data

If you need to retrieve a sub-set of the input data, you may use the `only` and `except` methods. Both of these methods will accept a single `array` or a dynamic list of arguments:
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']);

Expand All @@ -171,81 +180,93 @@ If you need to retrieve a sub-set of the input data, you may use the `only` and

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

#### 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 posted field like so:
#### Determining If An Input Value Is Present

$name = $request->name;
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:

When using dynamic properties, Laravel will first look for the parameter's value in the request payload and then in the route parameters.
if ($request->has('name')) {
//
}

<a name="old-input"></a>
### 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 services](/docs/{{version}}/validation), it is unlikely you will need to manually use these methods, as some of Laravel's built-in validation facilities will call them automatically.
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](/docs/{{version}}/validation), 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` instance will flash the current input to the [session](/docs/{{version}}/session) so that it is available during the user's next request to the application:
The `flash` method on the `Illuminate\Http\Request` class will flash the current input to the [session](/docs/{{version}}/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 sub-set of the request data into the session:
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');

#### Flash Input Into Session Then Redirect
#### Flashing Input Then Redirecting

Since you often will want to flash input in association with a redirect to the previous page, you may easily chain input flashing onto a redirect using the `withInput` method:
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('form')->withInput($request->except('password'));
return redirect('form')->withInput(
$request->except('password')
);

#### Retrieving Old Data
#### Retrieving Old Input

To retrieve flashed input from the previous request, use the `old` method on the `Request` instance. The `old` method provides a convenient helper for pulling the flashed input data out of the [session](/docs/{{version}}/session):
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](/docs/{{version}}/session):

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

Laravel also provides a global `old` helper function. If you are displaying old input within a [Blade template](/docs/{{version}}/blade), it is more convenient to use the `old` helper. If no old input exists for the given string, `null` will be returned:
Laravel also provides a global `old` helper. If you are displaying old input within a [Blade template](/docs/{{version}}/blade), it is more convenient to use the `old` helper. If no old input exists for the given field, `null` will be returned:

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

<a name="cookies"></a>
### Cookies

#### Retrieving Cookies From The Request
#### 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, you may use the `cookie` method on the `Illuminate\Http\Request` instance:
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:

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

#### Attaching A New Cookie To A Response
#### Attaching Cookies To Responses

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

Laravel provides a global `cookie` helper function which serves as a simple factory for generating new `Symfony\Component\HttpFoundation\Cookie` instances. The cookies may be attached to a `Illuminate\Http\Response` instance using the `withCookie` method:
return response('Hello World')->withCookie(
'name', 'value', $minutes
);

$response = new Illuminate\Http\Response('Hello World');
The `withCookie` 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](http://php.net/manual/en/function.setcookie.php) method:

$response->withCookie('name', 'value', $minutes);
return response('Hello World')->withCookie(
'name', 'value', $minutes, $path, $domain, $secure, $httpOnly
);

return $response;
#### Generating Cookie Instances

To create a long-lived cookie, which lasts for five years, you may use the `forever` method on the cookie factory by first calling the `cookie` helper with no arguments, and then chaining the `forever` method onto the returned cookie factory:
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:

$response->withCookie(cookie()->forever('name', 'value'));
$cookie = cookie('name', 'value', $minutes);

return response('Hello World')->withCookie($cookie);

<a name="files"></a>
### Files

#### Retrieving Uploaded Files

You may access uploaded files that are included with the `Illuminate\Http\Request` instance using the `file` method. The object returned by the `file` method is an instance of the `Symfony\Component\HttpFoundation\File\UploadedFile` class, which extends the PHP `SplFileInfo` class and provides a variety of methods for interacting with the file:
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:

$file = $request->file('photo');

$file = $request->photo;

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

if ($request->hasFile('photo')) {
Expand All @@ -260,13 +281,27 @@ In addition to checking if the file is present, you may verify that there were n
//
}

#### 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:

$path = $request->photo->path();

$extension = $request->photo->extension();

#### Moving Uploaded Files

To move the uploaded file to a new location, you should use the `move` method. This method will move the file from its temporary upload location (as determined by your PHP configuration) to a more permanent destination of your choosing:
To move the uploaded file to a new location, you should use the `move` method. This method will move the file from its temporary upload location (as determined by your PHP configuration) to a permanent destination of your choosing:

$request->file('photo')->move($destination);

$request->file('photo')->move($destination, $fileName);

When storing files it is common to store the files using a name that is a hash of the file's contents, which provides a unique identifier for the file. The `UploadedFile` class contains the `hashName` method which may be used to generate these paths. The file's contents will be hashed using the MD5 algorithm:

$request->file('photo')->move($destinationPath);
$name = $request->photo->hashName();

$request->file('photo')->move($destinationPath, $fileName);
$request->photo->move(storage_path('app/public'), $name);

#### Other File Methods

Expand Down

0 comments on commit 68e344e

Please sign in to comment.