ask
Illuminate\Http\Request
class on the controller. The incoming request instance will be automatically injected by the service container:<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class UserController extends Controller{ /** * 存储一个新用户。 * * @param Request $request * @return Response */ public function store(Request $request) { $name = $request->input('name'); // } }
Dependency Injection & Route ParametersIf your controller needs to get data from route parameters, you should include the parameters after other dependencies. For example, your route is defined like this: Route::put('user/{id}', 'UserController@update');
You can define the controller through the following method and use the Illuminate\Http\Request
class to get your route parametersid:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class UserController extends Controller{ /** * 更新指定用户 * * @param Request $request * @param string $id * @return Response */ public function update(Request $request, $id) { // } }
Get parameters through closure routingYou can also use Illuminate\Http\Request# in a routing closure ## class, the service container will automatically inject the request parameters into the routing closure:
use Illuminate\Http\Request; Route::get('/', function (Request $request) { // });
instance provides a series of methods to verify HTTP request parameters, and inherits the
Symfony\Component\HttpFoundation\Request class. The following are some important methods of this class: you can use PSR-7 standard defines the HTTP message interface, including requests and responses. If you want to use PSR-7 requests instead of Laravel requests, you need to install a few libraries first. Laravel uses the Symfony HTTP Message Bridge component to convert typical Laravel requests and responses into a PSR-7 compliant implementation: Once these libraries are installed, they can be passed in the route closure or control Use the request interface type hint in the controller method to get the PSR-7 request: {tip} If a PSR-7 response instance is returned from a route or controller, the framework will automatically convert it back to a Laravel response instance and displayed. By default, Laravel runs in the application’s global middleware stack Contains If you want to disable this behavior, just remove it from the Yes Use the Use some simple methods to get all the user's input through the The default value can be passed as the second parameter to the When working with a form containing an array input, use the "dot" operator to access array elements: Without parameters Call the If the query string value does not exist, ## The second parameter of the #queryGet the request path
path
The method returns the requested path information. So, if the requested path is http://domain.com/foo/bar
, the path
method will return foo/bar
:$uri = $request->path();
is
can verify whether the incoming request path matches the given pattern. In this method, you can also use *
characters as wildcards: if ($request->is('admin/*')) {
//
}
To get the request URL
url
or fullUrl
method to get the complete request URL. url
The method returns the URL that does not contain the query string. fullUrl
Gets the URL that contains the query string: // 不附带查询串...
$url = $request->url();
// 附带查询串...
$url = $request->fullUrl();
Get the request Method
method
The method returns the requested HTTP action. You can also use the isMethod
method to verify that the HTTP action matches the given guest: $method = $request->method();if ($request->isMethod('post')) {
//
}
PSR -7 Request
composer require symfony/psr-http-message-bridge
composer require zendframework/zend-diactoros
use Psr\Http\Message\ServerRequestInterface;
Route::get('/', function (ServerRequestInterface $request) {
//
});
Input clipping and normalization
TrimStrings
and ConvertEmptyStringsToNull
middleware. These middlewares are placed in the stack list of the App\Http\Kernel
class. They automatically trim all input string fields in the request, while converting empty string fields to null
. This way you don't have to worry about standardized conventions in routing and controllers. $middleware
attribute of the App\Http\Kernel
class (equivalent to removing it from the middle of the application removed from the file stack). Get input
Get all input data
all
method to get all input data arrays: $input = $request->all();
Get a single input value
Illuminate\Http\Request
instance. You don't need to worry about which user request is used. HTTP action. Regardless of the HTTP action, the user's request can be obtained by the input
method: $name = $request->input('name');
input
method. This value will be returned when the request does not include this parameter: $name = $request->input('name', 'Sally');
$name = $request->input('products.0.name');
$names = $request->input('products.*.name');
input
method to obtain all input values (in associative array form): $input = $request->input();
Get input from the query string
input The
method obtains the value from the entire request carrier (including the query string), and the query
method only obtains the value from the query string: $name = $request->query('name');
method will be returned as the default value of the parameter:
$name = $request->query('name', 'Helen');
query method without parameters to get all the values of the query string ( Associative array form):
$query = $request->query();Getting input through dynamic properties User input can be accessed through the dynamic properties of the
Illuminate\Http\Request instance. For example, if your application form contains the
name field, you can access the value of that field like this:
$name = $request->name;When using dynamic properties, Laravel first looks for the value of the parameter in the request body. If the value does not exist, Lavarel will search in the route parameters. Get JSON inputWhen passing a JSON request to the application, you can access the JSON data through the
input method, as long as the requested
The Content-Type header is set to
application/json. You can also use "dot" syntax to access JSON arrays:
$name = $request->input('user.name');Get part of the input dataIf you need to get a subset of the input data, you can use
only or
except method. They accept a single
array or a dynamic parameter list:
$input = $request->only(['username', 'password']); $input = $request->only('username', 'password'); $input = $request->except(['credit_card']); $input = $request->except('credit_card');
{tip}Determine whether the input value existsonly
The method returns all key-value pairs in the request; however, it does not return the request Key-value pair that does not exist in .
has method is used to determine whether the specified value exists in the request. If the value exists in the request, the
has method returns
true:
if ($request->has('name')) { // }If an array is given, the
has method will determine whether , whether all the specified values exist:
if ($request->has(['name', 'email'])) { // }If you want to determine whether a value exists in the request and is not empty, you need to use the
filled method:
if ($request->filled('name')) { // }
Old Data
Laravel allows you to persist data between requests. This feature is useful when repopulating a form after a validation error. However, if you use Lavarel's built-in validation features, you don't need to manually call these methods because some of Laravel's built-in validation features will automatically call them.
Transmit input data to Session
The
flash method of the Illuminate\Http\Request
class will transfer the current input Passed to the session, they are still available when the user makes this request to the application:
$request->flash();
You can use the flashOnly
or flashExcept
method to pass a subset of the request data to session. These methods are often used to exclude sensitive data such as passwords from session persistence:
$request->flashOnly(['username', 'email']);$request->flashExcept('password');
Transfer data and jump
When you often need to send input to session and then jump to the previous page, which can be easily achieved by calling the withInput
method after the jump function:
return redirect('form')->withInput(); return redirect('form')->withInput( $request->except('password') );
Get old data
To obtain the data transmitted by the previous request, you can use the old
method of the Request
instance. The old
method will pull the previously transmitted value from the session:
$username = $request->old('username');
Laravel also provides a global old
helper. If you want to display old data in a Blade template, the old
assistant is easier to use. If the old value for the given domain does not exist, it will return null
:
<input type="text" name="username" value="{{ old('username') }}">##Cookies
Get Cookies from the requestAll cookies generated by the Lavarel framework are encrypted and signed with an authorization code, which means that they will become invalid if changed by the client. . The cookie value can be obtained from the request using the
cookie method of the
Illuminate\Http\Request instance:
$value = $request->cookie('name');You can also use the
Cookie facade to access the cookie Value:
$value = Cookie::get('name');Attach Cookies to the responseYou can use the
cookie method to
Illuminate\Http\Response Attach cookies to the instance. You need to pass the name, value, and cookie expiration time (in minutes) to this method:
return response('Hello World')->cookie( 'name','value',$minutes );
cookie You can also accept several other less commonly used parameters. Usually these parameters have the same role and meaning as the parameters of PHP's built-in setcookie method:
return response('Hello World')->cookie( 'name', 'value', $minutes, $path, $domain, $secure, $httpOnly );Likewise, you can use the
Cookie facade to "arrange" the output from the application. Response cookies. The
queue method accepts a
Cookie instance or a list of parameters required to create a
Cookie. These cookies will be appended to the output response before being sent to the browser:
Cookie::queue(Cookie::make('name', 'value', $minutes)); Cookie::queue('name', 'value', $minutes);
Generate Cookie Instance
If you want to generate a Symfony\Component\HttpFoundation\Cookie
instance that can later be provided to the response instance, you can use the global cookie
assistant. This cookie will not be passed back to the client without being attached to the response instance:
$cookie = cookie('name', 'value', $minutes); return response('Hello World')->cookie($cookie);##FileGet the uploaded fileYou can use the
file method of the
Illuminate\Http\Request instance or Dynamic attribute access to uploaded files. The
file method returns an instance of the
Illuminate\Http\UploadedFile class, which extends from PHP's
SplFileInfo class and provides multiple methods for file interaction:
$file = $request->file('photo'); $file = $request->photo;You can use the
hasFile method to determine whether the specified file exists in the request:
if ($request->hasFile('photo')) { // }Verify successful uploadIn addition to verifying whether the file is exists, you can also use the
isValid method to verify whether there is any problem with the uploaded file:
if ($request->file('photo')->isValid()) { // }File path & extension
UploadedFile The class also contains methods to access the full path and extension of the file.
extension Method guesses the matching file extension based on the file's contents. This extension may be different from the extension provided by the client:
$path = $request->photo->path(); $extension = $request->photo->extension();Other file methods
UploadedFile There are several other examples. methods are available. Browse the API documentation for this class for more information on these methods.
store method of
UploadedFile to move the uploaded file to one of your disks, which could be a location on your local file system or even a cloud like Amazon S3 storage location. The
store method accepts a path relative to the root directory of the stored file configured in the file system. This path cannot contain a file name because the system automatically generates a unique ID as the file name.
store The method also accepts an optional second parameter, the name of the disk where the file is stored. This method returns the file path relative to the root of the disk:
$path = $request->photo->store('images'); $path = $request->photo->store('images', 's3');If you don't want to automatically generate the file name, you can use the
storeAs method, which accepts the path, file name, and disk name as its Parameters:
$path = $request->photo->storeAs('images', 'filename.jpg'); $path = $request->photo->storeAs('images', 'filename.jpg', 's3');
Configure Trusted Proxy
If your application is running behind a load balancer with an expired TLS/SSL certificate, you may notice that your application sometimes fails to generate HTTPS links. Typically this is because your application is forwarding traffic from the load balancer on port 80 without knowing whether it should generate a secure link.
Solving this problem requires including the App\Http\Middleware\TrustProxies
middleware in your Laravel application, which allows you to quickly customize the load balancer or proxy that your application trusts. Your trusted proxies should be listed as an array in the $proxies
property of this middleware. In addition to configuring trusted proxies, you can also configure which proxies should be trusted $header
:
<?php namespace App\Http\Middleware; use Illuminate\Http\Request; use Fideloper\Proxy\TrustProxies as Middleware; class TrustProxies extends Middleware{ /** * 应用程序的可信代理列表 * * @var array */ protected $proxies = [ '192.168.1.1', '192.168.1.2', ]; /** * 应该用来检测代理的头信息 * * @var string */ protected $headers = Request::HEADER_X_FORWARDED_ALL;}
{tip} If you use AWS Elastic Load Balancing, your
$header
The value should beRequest::HEADER_X_FORWARDED_AWS_ELB
. For more information on the constants available for the$headers
attribute, see Symfony's documentation on Trusting Proxies.
Trust all proxies
If you use Amazon AWS or another "cloud" load balancer provider, you may not know the actual IP address of the load balancer. In this case, you can use *
to trust all proxies:
/** * 应用程序的可信代理列表 * * @var array */ protected $proxies = '*';