HTTP Layer--Request

Source: Internet
Author: User

1. Visit Request Instance

To get the current HTTP request instance through dependency injection, you need to type-prompt the class in the Controller's constructor or method so that the Illuminate\Http\Request current request instance is automatically injected by the service container:

<?phpnamespace App\http\controllers;use Illuminate\http\request;use Illuminate\routing\controller;class Usercontroller extends controller{    /**     * Store new user     *     * @param Request $request     * @return Response     *    /Public function store (Request $request)    {        $name = $request->input (' name ');        //    }}

Dependency Injection & Routing Parameters

If your controller method also expects to get the routing parameters, simply place the route parameters after other dependencies, for example, if your route is defined as follows:

Route::p ut (' User/{id} ', ' [email protected] ');

You can still Illuminate\Http\Request access routing parameters for type hinting and to define controller methods as follows id :

<?phpnamespace app\http\controllers;use illuminate\http\request;classuser Controller extends controller{    /**     * Update specified user     *     * @param Request $request     * @param int $id     * @return Response    */Public function Update (Request $request, $id)    {        //    }}

Access requests by routing closures

You can also type a hint class on the routing closure Illuminate\Http\Request , and the service container will automatically inject the input request to the closure at execution time:

Use Illuminate\http\request; Route::get ('/', function (Request $request) {    //});
Request Path & method

Illuminate\Http\RequestThe instance provides several methods to detect an application's HTTP request, Laravel Illuminate\Http\Request inherits from the Symfony\Component\HttpFoundation\Request class, and illustrates some useful ways that the class provides:

Get Request Path

pathMethod will return the requested path information, so if the requested path is entered, the http://domain.com/foo/bar method will path return foo/bar :

$uri = $request->path ();

ismethod allows you to verify that incoming requests match the given pattern. You can use the wildcard character when using this method * :

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

Get Request URL

To get the full URL, not just the path information, you can use the or method provided by the request instance, and the method returns the url fullUrl url URL without the query string, and fullUrl the method returns the result that contains the query string:

Does not contain the query string $url= $request->url ();//contains the query string, \ n = $request->fullurl ();

Get Request method

methodMethod will return the HTTP request mode. You can also use isMethod methods to verify that HTTP requests match the given string:

$method = $request->method (), if ($request->ismethod (' post ')) {     //}
PSR-7 Request

The PSR-7 standard specifies the HTTP message interface, including requests and responses. If you want to get a PSR-7 request instance, first you need to install some libraries, Laravel use the Symfony HTTP Message Bridge component to translate the typical Laravel request and response into a compatible PSR-7 implementation:

Composer require symfony/psr-http-message-bridgecomposer require Zendframework/zend-diactoros

After installing these libraries, you only need to get the PSR-7 request in the routing or controller by typing the type hint on the request type:

Use Psr\http\message\serverrequestinterface; Route::get ('/', function (Serverrequestinterface $request) {    //});

Note: If the PSR-7 response instance is returned from the route or controller, it will automatically be converted to the Laravel response instance and displayed.

2. Get request Input

Get all input values

You can use all the method to get all the input values in an array format:

$input = $request->all ();

Get a single input value

With some simple methods, you can Illuminate\Http\Request access user input from an instance. You do not need to care about the HTTP request method used by the request, because the input to all requests is through the input method to get user input:

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

You can also pass a default value as the second parameter to input the method, and the value will be returned if the requested input value does not appear in the current request:

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

When working with table singular group input, you can use the "." To access the array input:

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

Getting input with dynamic properties

In addition, you can Illuminate\Http\Request access user input by using dynamic properties on the instance. For example, if your app form contains name fields, you can access the submitted values like this:

$name = $request->name;

With dynamic properties, Laravel first looks for the value of the parameter in the request, and if it does not, it is also found in the route parameter.

Get JSON input values

When sending a JSON request to the app, Content-Type you can get the JSON data through the method as long as the request header is set to, application/json input or through the "." Number resolved array:

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

Get the input part of the data

If you need to take out a subset of the input data, you can use the only or except method, both of which receive an array or a dynamic list as the unique parameter:

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

Determine if the input value appears

Determine whether the value appears in the request, you can use has the method, if the value has occurred and is not empty, the has method returns true :

if ($request->has (' name ')) {    //}
Last Request input

Laravel allows you to save input data between two requests, which is useful if you need to repopulate the form data after a failure to detect checksum data, but you do not need to use these methods manually if you are using Laravel built-in authentication services, because some Laravel The built-in check settings automatically call them.

Store input to a one-time Session

Illuminate\Http\RequestThe method of the instance flash stores the current input in a one-time session (so-called one-off refers to the data being taken from the session and the corresponding data is destroyed from the session) so that the data remains valid on the next request:

$request->flash ();

You can also use flashOnly and flashExcept methods to store the subset of input data in the session, which is useful for storing sensitive information outside the session:

$request->flashonly (' username ', ' email '), $request->flashexcept (' password ');

Store input to a one-time Session and redirect

If you often need to store input once and redirect to the previous page, you can simply use withInput the method to link the input data to the redirect following:

Return redirect (' form ')->withinput (), return redirect (' form ')->withinput ($request->except (' password '));

Remove Last Request data

To remove the last requested input data from the Session, you can use the method of the request instance old . oldmethod provides a convenient way to remove one-time data from the Session:

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

Laravel also provides a global helper function that, old if you are displaying the last input data in the Blade template, it is more convenient to use the helper function old , and NULL is returned if there is no corresponding input for the given parameter:

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

Remove cookies from the request

All cookies created by the Laravel framework are encrypted and signed with an authentication code, which means that they need to be validated if the client modifies them. We use Illuminate\Http\Request the method of the instance to cookie get the value of the cookie from the request:

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

New Cookie to response

You can use the cookie method to append a cookie to an instance of the output Illuminate\Http\Response , and you need to pass the name, value, and cookie expiration date (minutes) to this method:

Return response (' Hello World ')->cookie (    ' name ', ' value ', $minutes);

cookieThe method can receive some parameters that are less frequently used, and in general, these parameters are consistent with the PHP native function Setcookie function and meaning:

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

Generate Cookie Instance

If you want to generate an Symfony\Component\HttpFoundation\Cookie instance for subsequent attaching to the response instance, you can use a global helper function cookie that is sent to the client only if it is attached to the response instance:

$cookie = Cookie (' name ', ' value ', $minutes); return response (' Hello World ')->cookie ($cookie);
3. File Upload get the uploaded file

You can use Illuminate\Http\Request the method provided by the instance file or the dynamic property to access the upload file, and file the method returns an instance of the Illuminate\http\uploadedfile class that inherits from the class that provides the file interaction method from the PHP standard library SplFileInfo :

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

You can use hasFile the method to determine whether a file exists in the request:

if ($request->hasfile (' photo ')) {    //}

Verify that the file is uploaded successfully

Use isValid the method to determine if the file has errors during the upload process:

if ($request->file (' photo ')->isvalid ()) {    //}

File path & Extension

UploadedFileClass also provides methods for accessing the absolute path and extension of the uploaded file. extensionmethod can determine the file name extension based on the contents of the file, which may be inconsistent with the extension provided by the client:

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

Additional file methods

UploadedFileThere are many other methods available on the instance to view the API documentation for this class for more information.

Save the uploaded file

To save an uploaded file, you typically need to use one of the file systems you have configured, and UploadedFile the class has a store method that moves the uploaded file to the appropriate disk path, either somewhere on the local file system or a path on a cloud storage such as Amazon S3.

storeThe MD5 method receives a file-saved relative path (relative to the root of the file system configuration) and the path should not contain a file name because the file name is automatically generated by the content of the files.

storeThe method also receives an optional parameter--the disk name that is used to store the file as the second parameter, which returns the file path relative to the root directory:

$path = $request->photo->store (' images '); $path = $request->photo->store (' images ', ' S3 ');

If you do not want to generate the file name automatically, you can use the storeAs method, which receives the save path, file name, and disk name as parameters:

$path = $request->photo->storeas (' images ', ' filename.jpg ');
$path = $request->photo->storeas (' images ', ' filename.jpg ', ' S3 ');

HTTP Layer--Request

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.