Laravel Basic Tutorial--Request

Source: Internet
Author: User

HTTP request

Access Request

To make it easy to get an Http request instance through dependency injection, you should write the type declaration illuminate\http\request in the Controller's constructor or control function. The instance of the current request is automatically injected from the service container:

 
  Input (' name ');}  }

If your controller method also needs to receive parameters from the route, then you need to add the parameters to receive after the parameters of the dependency injection. For example, your route is defined as:

Route::p ut (' User/{id} ', ' usercontroller@update ');

Then you should first declare the dependency injection illuminate\http\reqeust, and then order the delivery route parameters:

    

Base Request Information

Illuminate\http\request instances provide a variety of methods for your app to check Http requests, which inherit from Symfony\component\httpfoundation\request. Here are some common ways to do this:

Retrieving the requested URI

The path method returns the requested URI. Therefore, when the destination address of the request is Http://domain.com/foo/bar, the path method returns Foo/bar:

$uri = $request->path ();

The Is method allows you to verify that the requested URI matches the provided pattern. You can use the * character as a wildcard character:

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

If you want the full path of the request, you can use the URL or the FullUrl method:

Without query string ... $url = $request->url ();//With Query string ... $url = $request->fullurl ();

You can also append the requested parameter information while obtaining the full request path, for example, if the target of the request is Http://domain.com/foo, the following method will return Http://domain.com/foo?bar=baz:

$url = $request->fullurlwithquery ([' Bar ' = ' baz ']);

How requests are retrieved

The methods method returns the HTTP request. You can also use the Ismethod method to match the HTTP request mode:

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

PSR-7 Request

The PSR-7 standard specifies a number of message interfaces for HTTP, including requests and responses. If you want to get an instance of the PSR-7 request, you need to install some support libraries first, laravel using Symfon HTTP Bridge Component to convert a typical laravel request and response to a PSR-7-compliant implementation:

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

Once you have these libraries installed, you can simply use the type hints in your routing or controller to get the PSR-7 request:

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

If the route or controller returns an instance of the PSR-7 response, it is automatically converted to the Laravel response instance.

Get input value

Gets the value entered

You can easily get the user's input value by illuminate\http\request the instance. And you don't have to care about how the user uses the Http request, you can get the value of all the requests by using the input method:

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

You can also pass the second argument to the input method, and if the value does not exist in the request, it will be returned as the default value:

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

When the form submits some input values that are arrays, you can use the. operator to access the array values in the request:

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

Gets the input value of the JSON request

You can also use the input method to access the JSON request, as long as the JSON request is set to the correct request header Content-type:application/json, then you can use. Syntax for in-depth access to arrays in JSON:

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

Determine if the input value exists

You can use the has method to determine if the request contains an input value for the user, and if the value is not an empty string, then the has method returns true:

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

Get all the input values

You can use the all method to get all the user input values that return an array that contains all the user values:

$input = $request->all ();

Get partial input value

You can use the only or except method to get a partial input value, both of which receive a separate array or a dynamic argument list:

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

Dynamic Properties

You can obtain the user's input value by using the dynamic properties of the Illuminat\http\request instance. If you have a name field in your app form, you can get the request field in the following way:

$name = $request->name;

When a dynamic property is used, Laravel first looks for the value in the request before retrieving the parameters in the route.

The old input

Laravel allows you to keep input for that request during the next request. This feature is especially useful in the case of form validation errors, which enable you to automatically populate the last request. If you use Laravel's authentication service, you don't need to call them manually, because Laravel's built-in validation mechanism automatically calls them.

Flash input to session

The Flash method of the Illuminate\http\request instance will flash the input of the current request to the session, allowing the app to be reused when accepting the user's next request:

$request->flash ();

You can also use the Flashonly and Flashexcept methods to flash part of the request input to the session:

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

Flash input to session and then jump

A common scenario is that you need to return to the previous page along with the user's input, so you can use the Withinput chaining method:

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

Get old input

You can use the old method to obtain the user request that was flash on the last request:

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

Laravel provides a global old help method. You can also use this method in the blade template, which returns null if the last request did not flash the input:

Cookies

Retrieving cookies from the request

All cookies in Laravel are created with an authentication code for visa encryption, which means that Laravel verifies the client's modifications to the cookie. You can use Illuminate\http\ Request instance Cookie method to obtain the cookie value:

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

Attach a new cookie to the response

Laravel provides a global cookie helper method to generate an Symfony\component\httpfoundation\cookie instance that can be illuminate\http\ Withcookie additions to the response instance:

$response = new Illuminate\http\response (' Hello World '); $response->withcookie (' name ', ' value ', $minutes); return $ Response

You can use the cookie method to create a long cookie up to 5 years, which requires you to call the Forever method directly using the cookie helper method without parameters:

$response->withcookie (Cookie ()->forever (' name ', ' value '));

File

Get the uploaded file

You can access the uploaded files via the Illuminate\http\request file method. The method returns an instance of the Symfony\component\httpfoundation\file\uploadedfile class that inherits from Splfileinfo and provides a variety of ways to interact with the file:

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

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

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

Verify that the file is uploaded successfully

You can use the IsValid method to verify that an error occurred during file upload:

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

Move the uploaded file

You can use the Move method to migrate uploaded files from the temporary directory to the specified directory:

$request->file (' photo ')->move ($destinationPath), $request->file (' photo ')->move ($destinationPath, $ FileName);

Additional file methods

UploadedFile There are many other methods available, you can view the API documentation for this class to learn more.

  • Related Article

    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.