Laravel basic tutorial-request-php Tutorial

Source: Internet
Author: User
Tags laravel tutorial
Basic laravel tutorial -- request an HTTP request

To easily obtain http Request instances through dependency injection, you should write the type declaration Illuminate \ Http \ Request in the controller's constructor or control function. The requested instance is automatically injected from the service container:

 input('name');  }}

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

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

Then you should first declare the dependency injection Illuminate \ Http \ Reqeust, and then pass the route parameters in order:

 Basic request information

The Illuminate \ Http \ Request instance provides multiple HTTP Request checking methods for your application. it inherits from Symfony \ Component \ HttpFoundation \ Request. Some common methods are listed here:

Retrieve the requested URI

The path method returns the requested URI. Therefore, when the target address of the request is http://domain.com/foo/bar, pathpattern will return foo/bar:

$uri = $request->path();

The is method allows you to verify whether the requested URI matches the provided mode. You can use the * character as the wildcard:

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

If you want to obtain the full path of the request, you can use the url or fullUrl method:

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

You can also append the request's parameter information while obtaining the complete request path, for example, if the request's target is a http://domain.com/foo, the following method will return the http://domain.com/foo? Bar = baz:

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

The method returns the HTTP request method. You can also use the isMethod method for http request matching:

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

The PSR-7 standard specifies message interfaces for http, including requests and responses. if you want to get an instance of a PSR-7 request, you need to first install some support libraries, laravel uses the Symfon HTTP Bridge component to convert typical laravel requests and responses to PSR-7-compatible implementations:

composer require symfony/psr-http-message-bridgecomposer require zendframework/zend-diactoros

Once you have installed these libraries, you can simply get PSR-7 requests using type prompts in your route or controller:

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 a laravel response instance.

Get input value get input value

You can use some methods of the Illuminate \ Http \ Request instance to easily obtain user input values. in addition, you do not need to care about the HTTP request method used by the user. you can use the input method to obtain the values of all request methods:

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

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

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

When some input values submitted in the form 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');
Obtains the input value of a JSON request.

You can also use the input method to access json requests. as long as the json request is set with the correct request header Content-Type: application/json, you can use it. syntax to access arrays in json:

$name = $request->input('user.name');
Determine whether the input value exists

You can use the has method to determine whether the request contains a user input value. if the value is not an empty string, the has Method returns true:

if ($request->has('name')) {  //}
Obtain all input values

You can use the all method to obtain all user input values. this method returns an array containing all user values:

$input = $request->all();
Obtain some input values

You can use the only or distinct t method to obtain some input values. both methods receive a separate array or dynamic parameter list:

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

You can use the dynamic attributes of the instance of Illuminat \ Http \ Request to obtain the user's input value. if the name field exists in your application form, you can use the following method to obtain the request field:

$name = $request->name;

When dynamic attributes are used, laravel first searches for whether the request contains the value before retrieving the parameters in the route.

Old input

Laravel allows you to maintain the input of this request during the next request. This feature is especially useful when form verification errors occur. it allows you to reuse the last request for automatic filling. If you use laravel's authentication service, you do not need to call them manually, because laravel's built-in authentication mechanism will automatically call 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, so that the application can reuse it when receiving the user's next Request:

$request->flash();

You can also use the flashOnly and flash0000t methods to input some flash requests to the session:

$request->flashOnly(['username', 'email']);$request->flashExcept('password');
Flash input to session next jump

A common scenario is that you need to return data to the previous page together with the user input. you can use the withInput chained 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 stored in the last request:

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

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

Cookies retrieve Cookies from requests

All cookies in laravel are encrypted by a verification code when they are created. This means that laravel verifies the client's modification to the cookie. you can use the cookie method of the Illuminate \ Http \ Request instance to obtain the cookie value:

$value = $request->cookie('name');
Append a new cookie to the response.

Laravel provides a global cookie help method to generate a Symfony \ Component \ HttpFoundation \ Cookie instance, which can be appended by withCookie of The Illuminate \ Http \ 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 5-year-long cookie. it requires you to directly call the forever method using the cookie help method without parameters:

$response->withCookie(cookie()->forever('name', 'value'));
Obtain the uploaded file

You can use the file method of Illuminate \ Http \ Request to access uploaded files. This method returns an instance of the Symfony \ Component \ HttpFoundation \ File \ UploadedFile class. it inherits from SplFileInfo and provides multiple File interaction methods:

$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 has been uploaded

You can use the isValid method to verify whether an error occurs during File upload:

if ($request->file('photo')->isValid()) {  //}
Move uploaded files

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);
Other file methods

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

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.