イントロダクションIntroduction
LaravelのIlluminate\Http\Requestクラスは、アプリケーションが処理している現在のHTTPリクエストを操作し、リクエストとともに送信される入力、クッキー、およびファイルを取得するオブジェクト指向の手段を提供しています。Laravel's
Illuminate\Http\Request class provides
an object-oriented way to interact with the current
HTTP request being handled by your application as
well as retrieve the input, cookies, and files that
were submitted with the request.
リクエストの操作Interacting With The Request
リクエストへのアクセスAccessing the Request
依存注入を使い、現在のHTTPリクエストのインスタンスを取得するには、ルートクロージャまたはコントローラメソッドでIlluminate\Http\Requestクラスをタイプヒントする必要があります。受信リクエストインスタンスは、Laravelサービスコンテナにより自動的に依存注入されます。To obtain an instance of the
current HTTP request via dependency injection, you
should type-hint the
Illuminate\Http\Request class on your
route closure or controller method. The incoming
request instance will automatically be injected by
the Laravel service
container[/docs/{{version}}/container]:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
class UserController extends Controller
{
/**
* 新しいユーザーを保存
*/
public function store(Request $request): RedirectResponse
{
$name = $request->input('name');
// Store the user...
return redirect('/users');
}
}
前述のように、ルートクロージャでIlluminate\Http\Requestクラスをタイプヒントすることもできます。サービスコンテナは、実行時に受信リクエストをクロージャへ自動で依存挿入します。As mentioned, 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) {
// ...
});
依存注入とルートパラメータDependency Injection and 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:
use App\Http\Controllers\UserController;
Route::put('/user/{id}', [UserController::class, 'update']);
以下のようにコントローラメソッドを定義することで、Illuminate\Http\Requestをタイプヒントし、idルートパラメーターにアクセスできます。You may still type-hint the
Illuminate\Http\Request and access your
id route parameter by defining your
controller method as follows:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
class UserController extends Controller
{
/**
* 指定ユーザーを更新
*/
public function update(Request $request, string $id): RedirectResponse
{
// ユーザーの更新処理…
return redirect('/users');
}
}
リクエストパスとホスト、メソッドRequest Path, Host, and Method
Illuminate\Http\Requestインスタンスは、Symfony\Component\HttpFoundation\Requestクラスを拡張し、受信HTTPリクエストを調べるためのさまざまなメソッドを提供しています。以下では、もっとも重要なメソッドからいくつか説明します。The
Illuminate\Http\Request instance
provides a variety of methods for examining the
incoming HTTP request and extends the
Symfony\Component\HttpFoundation\Request
class. We will discuss a few of the most important
methods below.
リクエストパスの取得Retrieving the Request Path
pathメソッドはリクエストのパス情報を返します。ですから、受信リクエストがhttp://example.com/foo/barをターゲットにしている場合、pathメソッドはfoo/barを返します。The path method
returns the request's path information. So, if the
incoming request is targeted at
http://example.com/foo/bar, the
path method will return
foo/bar:
$uri = $request->path();
リクエストパス/ルートの検査Inspecting the Request Path / Route
isメソッドを使用すると、受信リクエストパスが特定のパターンに一致することを判定できます。このメソッドでは、ワイルドカードとして*文字を使用できます。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/*')) {
// ...
}
routeIsメソッドを使用して、受信リクエストが名前付きルートに一致するかを判定できます。Using the routeIs
method, you may determine if the incoming request
has matched a named
route[/docs/{{version}}/routing#named-routes]:
if ($request->routeIs('admin.*')) {
// ...
}
リクエストURLの取得Retrieving the Request URL
受信リクエストの完全なURLを取得するには、urlまたはfullUrlメソッドを使用できます。urlメソッドはクエリ文字列を含まないURLを返し、fullUrlメソッドはクエリ文字列も含みます。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:
$url = $request->url();
$urlWithQueryString = $request->fullUrl();
現在のURLへクエリ文字列のデータを追加したい場合は、fullUrlWithQueryメソッドを呼び出します。このメソッドは、与えられたクエリ文字列変数の配列を現在のクエリ文字列にマージします。If you would like to append query
string data to the current URL, you may call the
fullUrlWithQuery method. This method
merges the given array of query string variables
with the current query string:
$request->fullUrlWithQuery(['type' => 'phone']);
指定されたクエリ文字列パラメータなしの、現在のURLを取得したい場合は、fullUrlWithoutQueryメソッドを利用します。If you would like to get the
current URL without a given query string parameter,
you may utilize the fullUrlWithoutQuery
method:
$request->fullUrlWithoutQuery(['type']);
リクエストホストの取得Retrieving the Request Host
host、httpHost、schemeAndHttpHostメソッドを使い、受信リクエストの「ホスト」を取得できます。You may retrieve the
"host" of the incoming request via the
host, httpHost, and
schemeAndHttpHost methods:
$request->host();
$request->httpHost();
$request->schemeAndHttpHost();
リクエストメソッドの取得Retrieving the Request Method
methodメソッドは、リクエストのHTTP動詞を返します。isMethodメソッドを使用して、HTTP動詞が特定の文字列と一致するか判定できます。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();
if ($request->isMethod('post')) {
// ...
}
リクエストヘッダRequest Headers
headerメソッドを使用して、Illuminate\Http\Requestインスタンスからリクエストヘッダを取得できます。リクエストにヘッダが存在しない場合、nullを返します。ただし、headerメソッドは、リクエストにヘッダが存在しない場合に返す2番目の引数をオプションとして取ります。You may retrieve a request header
from the Illuminate\Http\Request
instance using the header method. If
the header is not present on the request,
null will be returned. However, the
header method accepts an optional
second argument that will be returned if the header
is not present on the request:
$value = $request->header('X-Header-Name');
$value = $request->header('X-Header-Name', 'default');
hasHeaderメソッドを使用して、リクエストに特定のヘッダが含まれているか判定できます。The hasHeader method
may be used to determine if the request contains a
given header:
if ($request->hasHeader('X-Header-Name')) {
// ...
}
便利なように、bearerTokenメソッドをAuthorizationヘッダからのBearerトークン取得で使用できます。そのようなヘッダが存在しない場合、空の文字列が返されます。For convenience, the
bearerToken method may be used to
retrieve a bearer token from the
Authorization header. If no such header
is present, an empty string will be
returned:
$token = $request->bearerToken();
リクエストIPアドレスRequest IP Address
ipメソッドを使用して、アプリケーションにリクエストを送信したクライアントのIPアドレスを取得できます。The ip method may be
used to retrieve the IP address of the client that
made the request to your application:
$ipAddress = $request->ip();
プロキシによって転送された、すべてのクライアントIPアドレスを含むIPアドレスの配列を取得したい場合は、ipsメソッドを使用してください。「元(original)」のクライアントIPアドレスは配列の最後になります。If you would like to retrieve an
array of IP addresses, including all of the client
IP addresses that were forwarded by proxies, you may
use the ips method. The
"original" client IP address will be at
the end of the array:
$ipAddresses = $request->ips();
一般的に、IPアドレスは信頼できないユーザーが制御できる入力と見なし、情報提供のみを目的として使用するべきでしょう。In general, IP addresses should be considered untrusted, user-controlled input and be used for informational purposes only.
コンテントネゴシエーションContent Negotiation
Laravelは、Acceptヘッダを介して受信リクエストへリクエストされたコンテンツタイプを検査するメソッドをいくつか提供しています。まず、getAcceptableContentTypesメソッドは、リクエストが受付可能なすべてのコンテンツタイプを含む配列を返します。Laravel provides several methods
for inspecting the incoming request's requested
content types via the Accept header.
First, the getAcceptableContentTypes
method will return an array containing all of the
content types accepted by the request:
$contentTypes = $request->getAcceptableContentTypes();
acceptsメソッドはコンテンツタイプの配列を受け入れ、いずれかのコンテンツタイプがリクエストにより受け入れられた場合はtrueを返します。それ以外の場合は、falseが返ります。The accepts method
accepts an array of content types and returns
true if any of the content types are
accepted by the request. Otherwise,
false will be returned:
if ($request->accepts(['text/html', 'application/json'])) {
// ...
}
prefersメソッドを使用して、特定のコンテンツタイプの配列のうち、リクエストで最も優先されるコンテンツタイプを決定できます。指定したコンテンツタイプのいずれもがリクエストで受け入れられない場合、nullが返ります。You may use the
prefers method to determine which
content type out of a given array of content types
is most preferred by the request. If none of the
provided content types are accepted by the request,
null will be returned:
$preferred = $request->prefers(['text/html', 'application/json']);
多くのアプリケーションはHTMLまたはJSONのみを提供するため、expectsJsonメソッドを使用して、受信リクエストがJSONリクエストを期待しているかを手早く判定できます。Since many applications only
serve HTML or JSON, you may use the
expectsJson method to quickly determine
if the incoming request expects a JSON
response:
if ($request->expectsJson()) {
// ...
}
PSR-7リクエストPSR-7 Requests
PSR-7標準は、リクエストとレスポンスを含むHTTPメッセージのインターフェイスを規定しています。Laravelリクエストの代わりにPSR-7リクエストのインスタンスを取得したい場合は、最初にいくつかのライブラリをインストールする必要があります。LaravelはSymfony HTTP Message Bridgeコンポーネントを使用して、通常使用するLaravelのリクエストとレスポンスをPSR-7互換の実装に変換します。The PSR-7 standard[https://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 nyholm/psr7
これらのライブラリをインストールしたら、ルートクロージャまたはコントローラメソッドでリクエストインターフェイスをタイプヒントすることで、PSR-7リクエストを取得できます。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) {
// ...
});
Note: ルートまたはコントローラからPSR-7レスポンスインスタンスを返すと、自動的にLaravelレスポンスインスタンスに変換され、フレームワークによって表示されます。[!NOTE]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.
入力Input
入力の取得Retrieving Input
全入力データの取得Retrieving All Input Data
allメソッドを使用して、受信リクエストのすべての入力データをarrayとして取得できます。このメソッドは、受信リクエストがHTMLフォームからのものであるか、XHRリクエストであるかに関係なく使用できます。You may retrieve all of the
incoming request's input data as an
array using the all
method. This method may be used regardless of
whether the incoming request is from an HTML form or
is an XHR request:
$input = $request->all();
collectメソッドを使うと、受信リクエストのすべての入力データをコレクションとして取り出せます。Using the collect
method, you may retrieve all of the incoming
request's input data as a
collection[/docs/{{version}}/collections]:
$input = $request->collect();
collectメソッドでも、入力されたリクエストのサブセットをコレクションとして取得できます。The collect method
also allows you to retrieve a subset of the incoming
request's input as a collection:
$request->collect('users')->each(function (string $user) {
// ...
});
単一入力値の取得Retrieving an Input Value
いくつかの簡単な方法を使用すれば、リクエストに使用されたHTTP動詞を気にすることなく、Illuminate\Http\Requestインスタンスからのすべてのユーザー入力にアクセスできます。HTTP動詞に関係なく、inputメソッドを使用してユーザー入力を取得できます。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');
inputメソッドの2番目の引数としてデフォルト値を渡すことができます。指定した入力値がリクエストに存在しない場合、この値を返します。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 with forms that contain array inputs, use "dot" notation to access the arrays:
$name = $request->input('products.0.name');
$names = $request->input('products.*.name');
すべての入力値を連想配列として取得するために、引数なしでinputメソッドを呼び出せます。You may call the
input method without any arguments in
order to retrieve all of the input values as an
associative array:
$input = $request->input();
クエリ文字列からの入力の取得Retrieving Input From the Query String
inputメソッドはリクエストペイロード全体(クエリ文字列を含む)から値を取得しますが、queryメソッドはクエリ文字列からのみ値を取得します。While the input
method retrieves values from the entire request
payload (including the query string), the
query method will only retrieve values
from the query string:
$name = $request->query('name');
指定したクエリ文字列値データが存在しない場合、このメソッドの2番目の引数を返します。If the requested query string value data is not present, the second argument to this method will be returned:
$name = $request->query('name', 'Helen');
すべてのクエリ文字列値を連想配列として取得するために、引数なしでqueryメソッドを呼び出せます。You may call the
query method without any arguments in
order to retrieve all of the query string values as
an associative array:
$query = $request->query();
JSON入力値の取得Retrieving JSON Input Values
JSONリクエストをアプリケーションに送信する場合、リクエストのContent-Typeヘッダが適切にapplication/jsonへ設定されている限り、inputメソッドを介してJSONデータにアクセスできます。「ドット」構文を使用して、JSON配列/オブジェクト内にネストされている値を取得することもできます。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 retrieve
values that are nested within JSON arrays /
objects:
$name = $request->input('user.name');
Stringable入力値の取得Retrieving Stringable Input Values
リクエストの入力データをプリミティブなstringとして取得する代わりに、stringメソッドを使用して、リクエストデータを
Illuminate\Support\Stringableのインスタンスとして取得可能です。Instead of retrieving the
request's input data as a primitive
string, you may use the
string method to retrieve the request
data as an instance of
Illuminate\Support\Stringable[/docs/{{version}}/helpers#fluent-strings]:
$name = $request->string('name')->trim();
論理入力値の取得Retrieving Boolean Input Values
チェックボックスなどのHTML要素を処理する場合、アプリケーションは実際には文字列である「真の」値を受け取る可能性があります。たとえば、「true」または「on」です。使いやすいように、booleanメソッドを使用してこれらの値をブール値として取得できます。booleanメソッドは、1、"1"、true、"true"、"on"、"yes"に対してtrueを返します。他のすべての値はfalseを返します。When dealing with HTML elements
like checkboxes, your application may receive
"truthy" values that are actually strings.
For example, "true" or "on". For
convenience, you may use the boolean
method to retrieve these values as booleans. The
boolean method returns
true for 1, "1", true,
"true", "on", and
"yes". All other values will return
false:
$archived = $request->boolean('archived');
データ入力値の取得Retrieving Date Input Values
便利なように、日付や時刻を含む入力値は、dateメソッドを用いてCarbonインスタンスとして取得できます。もし、リクエストに指定した名前の入力値が含まれていない場合は、nullを返します。For convenience, input values
containing dates / times may be retrieved as Carbon
instances using the date method. If the
request does not contain an input value with the
given name, null will be
returned:
$birthday = $request->date('birthday');
dateメソッドの第2、第3引数は、それぞれ日付のフォーマットとタイムゾーンを指定するために使用します。The second and third arguments
accepted by the date method may be used
to specify the date's format and timezone,
respectively:
$elapsed = $request->date('elapsed', '!H:i', 'Europe/Madrid');
入力値が存在するがフォーマットが無効な場合は、InvalidArgumentExceptionを投げます。したがって、dateメソッドを呼び出す前に入力値をバリデーションすることを推奨します。If the input value is present but
has an invalid format, an
InvalidArgumentException will be
thrown; therefore, it is recommended that you
validate the input before invoking the
date method.
Enum入力値の取得Retrieving Enum Input Values
PHPのenumに対応する入力値も、リクエストから取得することがあります。リクエストに指定した名前の入力値が含まれていない場合、あるいは入力値にマッチするenumバッキング値をそのenumが持たない場合、nullを返します。enumメソッドは、入力値の名前とenumクラスを第1引数、第2引数に取ります。Input values that correspond to
PHP
enums[https://www.php.net/manual/en/language.types.enumerations.php]
may also be retrieved from the request. If the
request does not contain an input value with the
given name or the enum does not have a backing value
that matches the input value, null will
be returned. The enum method accepts
the name of the input value and the enum class as
its first and second arguments:
use App\Enums\Status;
$status = $request->enum('status', Status::class);
動的プロパティを介した入力の取得Retrieving Input via Dynamic Properties
Illuminate\Http\Requestインスタンスの動的プロパティを使用してユーザー入力にアクセスすることもできます。たとえば、アプリケーションのフォームの1つにnameフィールドが含まれている場合、次のようにフィールドの値にアクセスできます。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:
$name = $request->name;
動的プロパティを使用する場合、Laravelは最初にリクエストペイロードでパラメータの値を探します。見つからない場合、Laravelは一致したルートのパラメーターの中のフィールドを検索します。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 matched route's parameters.
入力データの一部の取得Retrieving a Portion of the Input Data
入力データのサブセットを取得する必要がある場合は、onlyメソッドとexceptメソッドを使用できます。これらのメソッドは両方とも、単一の「配列」または引数の動的リストを受け入れます。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']);
$input = $request->only('username', 'password');
$input = $request->except(['credit_card']);
$input = $request->except('credit_card');
Warning!
onlyメソッドは、指定したすべてのキー/値ペアを返します。ただし、リクエスト中に存在しないキー/値ペアは返しません。[!WARNING]Theonlymethod returns all of the key / value pairs that you request; however, it will not return key / value pairs that are not present on the request.
入力の存在Input Presence
hasメソッドを使用して、リクエストに値が存在するかを判定できます。リクエストに値が存在する場合、hasメソッドはtrueを返します。You may use the has
method to determine if a value is present on the
request. The has method returns
true if the value is present on the
request:
if ($request->has('name')) {
// ...
}
配列が指定されると、hasメソッドは、指定されたすべての値が存在するかどうかを判別します。When given an array, the
has method will determine if all of the
specified values are present:
if ($request->has(['name', 'email'])) {
// ...
}
hasAnyメソッドは、指定値のいずれかが存在すれば、true
を返します。The hasAny
method returns true if any of the
specified values are present:
if ($request->hasAny(['name', 'email'])) {
// ...
}
リクエストに値が存在する場合、whenHasメソッドは指定するクロージャを実行します。The whenHas method
will execute the given closure if a value is present
on the request:
$request->whenHas('name', function (string $input) {
// ...
});
whenHasメソッドには、指定した値がリクエストに存在しない場合に実行する2つ目のクロージャを渡せます。A second closure may be passed to
the whenHas method that will be
executed if the specified value is not present on
the request:
$request->whenHas('name', function (string $input) {
// "name"が存在する場合の処理…
}, function () {
// "name"が存在しない場合の処理…
});
リクエストに値が存在し、空文字列でないことを判断したい場合は、filledメソッドを使用します。If you would like to determine if
a value is present on the request and is not an
empty string, you may use the filled
method:
if ($request->filled('name')) {
// ...
}
anyFilledメソッドは、指定値のいずれかが空文字列でなければ、trueを返します。The anyFilled method
returns true if any of the specified
values is not an empty string:
if ($request->anyFilled(['name', 'email'])) {
// ...
}
値がリクエストに存在し、空文字列でない場合、whenFilledメソッドは指定したクロージャを実行します。The whenFilled
method will execute the given closure if a value is
present on the request and is not an empty
string:
$request->whenFilled('name', function (string $input) {
// ...
});
whenFilledメソッドには、指定した値が空だった場合に実行する2つ目のクロージャを渡せます。A second closure may be passed to
the whenFilled method that will be
executed if the specified value is not
"filled":
$request->whenFilled('name', function (string $input) {
// "name"の値が空でない場合の処理…
}, function () {
// "name"の値が空の場合の処理…
});
特定のキーがリクエストに含まれていないかを判定するには、missingおよびwhenMissingメソッドが使用できます。To determine if a given key is
absent from the request, you may use the
missing and whenMissing
methods:
if ($request->missing('name')) {
// ...
}
$request->whenMissing('name', function (array $input) {
// "name"の値がない
}, function () {
// "name"が存在する場合の処理…
});
追加入力のマージMerging Additional Input
リクエスト中の既存の入力データへ、追加の入力を自分でマージする必要が起きることも時にはあるでしょう。これはmergeメソッドを使用し実現できます。指定入力キーが既にリクエストで存在している場合、mergeメソッドへ指定したデータで上書きされます。Sometimes you may need to
manually merge additional input into the request's
existing input data. To accomplish this, you may use
the merge method. If a given input key
already exists on the request, it will be
overwritten by the data provided to the
merge method:
$request->merge(['votes' => 0]);
mergeIfMissingメソッドは、リクエストの入力データ内に対応するキーがまだ存在しない場合に、入力をリクエストにマージするために使用します。The mergeIfMissing
method may be used to merge input into the request
if the corresponding keys do not already exist
within the request's input data:
$request->mergeIfMissing(['votes' => 0]);
直前の入力Old Input
Laravelは、今のリクエストから次のリクエストまで入力を保持できます。この機能は、バリデーションエラーを検出した後にフォームを再入力するときに特に便利です。ただし、Laravelのバリデーション機能を使用する場合、これらのセッション入力一時保持メソッドを手作業で直接使用する必要がないかもしれません。Laravelに組み込まれているバリデーション機能のように、一時保持入力を自動で呼び出すからです。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 possible that you will not need to manually use these session input flashing methods directly, as some of Laravel's built-in validation facilities will call them automatically.
セッションへ入力の一時保持Flashing Input to the Session
Illuminate\Http\Requestクラスのflashメソッドは、セッションへ現在の入力を一時保持して、ユーザーがアプリケーションに次にリクエストするときに使用できるようにします。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();
flashOnlyメソッドとflashExceptメソッドを使用して、リクエストデータのサブセットをセッションへ一時保持することもできます。これらの方法は、パスワードなどの機密情報をセッションから除外するのに役立ちます。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');
入力を一時保持後のリダイレクトFlashing Input Then Redirecting
多くの場合、セッションへ入力を一時保持してから前のページにリダイレクトする必要があるため、withInputメソッドを使用して、リダイレクトへ簡単にチェーンで入力の一時保持を指示できます。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()->route('user.create')->withInput();
return redirect('form')->withInput(
$request->except('password')
);
直前の入力の取得Retrieving Old Input
前のリクエストで一時保持した入力を取得するには、Illuminate\Http\Requestのインスタンスでoldメソッドを呼び出します。oldメソッドは、以前に一時保持した入力データをセッションから取得します。To retrieve flashed input from
the previous request, invoke the old
method on an instance of
Illuminate\Http\Request. The
old method will pull the previously
flashed input data from the
session[/docs/{{version}}/session]:
$username = $request->old('username');
Laravelはグローバルなoldヘルパも提供しています。Bladeテンプレート内に古い入力を表示する場合は、oldヘルパを使用してフォームを再入力する方が便利です。指定されたフィールドに古い入力が存在しない場合、nullを返します。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
to repopulate the form. If no old input exists for
the given field, null will be
returned:
<input type="text" name="username" value="{{ old('username') }}">
クッキーCookies
リクエストからクッキーを取得Retrieving Cookies From Requests
Laravelフレームワークが作成する、すべてのクッキーは暗号化され、認証コードで署名されています。つまり、クライアントによって変更された場合、クッキーは無効と見なします。リクエストからクッキー値を取得するには、Illuminate\Http\Requestインスタンスでcookieメソッドを使用します。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 an
Illuminate\Http\Request
instance:
$value = $request->cookie('name');
入力のトリムと正規化Input Trimming and Normalization
Laravelはデフォルトで、アプリケーションのグローバルミドルウェアスタックにIlluminate\Foundation\Http\Middleware\TrimStringsとIlluminate\Foundation\Http\Middleware\ConvertEmptyStringsToNullミドルウェアを用意してす。これらのミドルウェアは、リクエスト上の受信したすべての文字列フィールドを自動的にトリムし、空の文字列フィールドをnullへ変換します。これにより、ルートやコントローラで正規化の心配をする必要がなくなります。By default, Laravel includes the
Illuminate\Foundation\Http\Middleware\TrimStrings
and
Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull
middleware in your application's global middleware
stack. These middleware will automatically trim all
incoming string fields on the request, as well as
convert any empty string fields to
null. This allows you to not have to
worry about these normalization concerns in your
routes and controllers.
入力ノーマライズの無効化Disabling Input Normalization
すべてのリクエストに対してこの動作を無効にしたい場合は、アプリケーションのbootstrap/app.phpファイルで
$middleware->removeメソッドを呼び出し、アプリケーションのミドルウェアスタックから2つのミドルウェアを削除してください。If you would like to disable this
behavior for all requests, you may remove the two
middleware from your application's middleware stack
by invoking the $middleware->remove
method in your application's
bootstrap/app.php file:
use Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull;
use Illuminate\Foundation\Http\Middleware\TrimStrings;
->withMiddleware(function (Middleware $middleware) {
$middleware->remove([
ConvertEmptyStringsToNull::class,
TrimStrings::class,
]);
})
アプリケーションへのリクエストのサブセットに対して、文字列のトリミングと空文字列の変換を無効にしたい場合は、アプリケーションのbootstrap/app.phpファイル内でtrimStringsとconvertEmptyStringsToNullミドルウェアメソッドを使用してください。どちらのメソッドもクロージャの配列を引数に取ります。クロージャはtrueまたはfalseを返し、入力の正規化をスキップするかを決めます。If you would like to disable
string trimming and empty string conversion for a
subset of requests to your application, you may use
the trimStrings and
convertEmptyStringsToNull middleware
methods within your application's
bootstrap/app.php file. Both methods
accept an array of closures, which should return
true or false to indicate
whether input normalization should be
skipped:
->withMiddleware(function (Middleware $middleware) {
$middleware->convertEmptyStringsToNull(except: [
fn (Request $request) => $request->is('admin/*'),
]);
$middleware->trimStrings(except: [
fn (Request $request) => $request->is('admin/*'),
]);
})
ファイルFiles
アップロード済みファイルの取得Retrieving Uploaded Files
アップロードしたファイルは、fileメソッドまたは動的プロパティを使用してIlluminate\Http\Requestインスタンスから取得できます。fileメソッドはIlluminate\Http\UploadedFileクラスのインスタンスを返します。これは、PHPのSplFileInfoクラスを拡張し、ファイルを操作するさまざまなメソッドを提供しています。You may retrieve uploaded files
from an 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;
hasFileメソッドを使用して、リクエストにファイルが存在するか判定できます。You may determine if a file is
present on the request using the
hasFile method:
if ($request->hasFile('photo')) {
// ...
}
正常なアップロードのバリデーションValidating Successful Uploads
ファイルが存在するかどうかを判定することに加え、isValidメソッドによりファイルのアップロードに問題がなかったことを確認できます。In addition to checking if the
file is present, you may verify that there were no
problems uploading the file via the
isValid method:
if ($request->file('photo')->isValid()) {
// ...
}
ファイルパスと拡張子File Paths and Extensions
UploadedFileクラスは、ファイルの完全修飾パスとその拡張子にアクセスするためのメソッドも用意しています。extensionメソッドは、その内容に基づいてファイルの拡張子を推測しようとします。この拡張機能は、クライアントが提供した拡張子とは異なる場合があります。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();
その他のファイルメソッドOther File Methods
他にもUploadedFileインスタンスで利用できる様々なメソッドがあります。これらのメソッドに関する詳細な情報は、クラスの
API ドキュメントを参照してください。There are a variety of other
methods available on UploadedFile
instances. Check out the API documentation for
the
class[https://github.com/symfony/symfony/blob/6.0/src/Symfony/Component/HttpFoundation/File/UploadedFile.php]
for more information regarding these
methods.
アップロード済みファイルの保存Storing Uploaded Files
アップロードされたファイルを保存するには、設定済みのファイルシステムのいずれかを通常使用します。UploadedFileクラスにはstoreメソッドがあり、アップロードされたファイルをディスクの1つに移動します。ディスクは、ローカルファイルシステム上の場所やAmazon
S3のようなクラウドストレージの場所である可能性があります。To store an uploaded file, you
will typically use one of your configured
filesystems[/docs/{{version}}/filesystem].
The UploadedFile class has a
store method that will move an uploaded
file to one of your disks, which may be a location
on your local filesystem or a cloud storage location
like Amazon S3.
storeメソッドは、ファイルシステムの設定済みルートディレクトリを基準にしてファイルを保存するパスを引数に取ります。ファイル名として機能する一意のIDが自動的に生成されるため、このパスにはファイル名を含めることはできません。The store method
accepts the path where the file should be stored
relative to the filesystem's configured root
directory. This path should not contain a filename,
since a unique ID will automatically be generated to
serve as the filename.
storeメソッドは、ファイルの保存に使用するディスクの名前を第2引数にオプションとして取ります。このメソッドは、ディスクのルートを基準にしたファイルのパスを返します。The store method
also accepts an optional second argument for the
name of the disk that should be used to store the
file. The method will return the path of the file
relative to the disk's root:
$path = $request->photo->store('images');
$path = $request->photo->store('images', 's3');
ファイル名を自動的に生成したくない場合は、パス、ファイル名、およびディスク名を引数として受け入れるstoreAsメソッドが使用できます。If you do not want a filename to
be automatically generated, you may use the
storeAs method, which accepts the path,
filename, and disk name as its arguments:
$path = $request->photo->storeAs('images', 'filename.jpg');
$path = $request->photo->storeAs('images', 'filename.jpg', 's3');
Note: Laravelのファイルストレージの詳細は、完全なファイルストレージドキュメントを確認してください。[!NOTE]For more information about file storage in Laravel, check out the complete file storage documentation[/docs/{{version}}/filesystem].
信頼するプロキシの設定Configuring Trusted Proxies
TLS/SSL証明書を末端とするロードバランサーの背後でアプリケーションを実行している場合、urlヘルパを使用するとアプリケーションがHTTPSリンクを生成しないことがあります。通常、これは、アプリケーションがポート80でロードバランサーからトラフィックを転送していて、安全なリンクを生成する必要があることを認識していないためです。When running your applications
behind a load balancer that terminates TLS / SSL
certificates, you may notice your application
sometimes does not generate HTTPS links when using
the url helper. Typically this is
because your application is being forwarded traffic
from your load balancer on port 80 and does not know
it should generate secure links.
これを解決するには、Laravelアプリケーションが用意しているIlluminate\Http\Middleware\TrustProxiesミドルウェアを有効にして、アプリケーションが信頼するロードバランサーやプロキシを手早くカスタマイズしてください。信頼するプロキシは、アプリケーションのbootstrap/app.phpファイルでtrustProxiesミドルウェアメソッドを使用し指定します。To solve this, you may enable the
Illuminate\Http\Middleware\TrustProxies
middleware that is included in your Laravel
application, which allows you to quickly customize
the load balancers or proxies that should be trusted
by your application. Your trusted proxies should be
specified using the trustProxies
middleware method in your application's
bootstrap/app.php file:
->withMiddleware(function (Middleware $middleware) {
$middleware->trustProxies(at: [
'192.168.1.1',
'192.168.1.2',
]);
})
信頼するプロキシを設定することに加え、信頼すべきプロキシヘッダを設定することもできます。In addition to configuring the trusted proxies, you may also configure the proxy headers that should be trusted:
->withMiddleware(function (Middleware $middleware) {
$middleware->trustProxies(headers: Request::HEADER_X_FORWARDED_FOR |
Request::HEADER_X_FORWARDED_HOST |
Request::HEADER_X_FORWARDED_PORT |
Request::HEADER_X_FORWARDED_PROTO |
Request::HEADER_X_FORWARDED_AWS_ELB
);
})
Note: AWS Elastic Load Balancingを使用している場合、
headersの値はRequest::HEADER_X_FORWARDED_AWS_ELBでなければなりません。headersの値で使用できる定数の詳細については、Symfonyのドキュメント、信頼するプロキシを参照してください。[!NOTE]If you are using AWS Elastic Load Balancing, yourheadersvalue should beRequest::HEADER_X_FORWARDED_AWS_ELB. For more information on the constants that may be used in theheadersvalue, check out Symfony's documentation on trusting proxies[https://symfony.com/doc/7.0/deployment/proxies.html].
すべてのプロキシを信頼するTrusting All Proxies
Amazon
AWSまたは別の「クラウド」ロードバランサープロバイダを使用している場合、実際のバランサーのIPアドレスがわからない場合があります。この場合、*を使用してすべてのプロキシを信頼できます。If you are using Amazon AWS or
another "cloud" load balancer provider,
you may not know the IP addresses of your actual
balancers. In this case, you may use *
to trust all proxies:
->withMiddleware(function (Middleware $middleware) {
$middleware->trustProxies(at: '*');
})
信頼するホストの設定Configuring Trusted Hosts
デフォルトでLaravelは、HTTPリクエストのHostヘッダの内容に関わらず、受け取った全てのリクエストに応答します。また、Webリクエスト中にアプリケーションへの絶対的なURLを生成する際には、Hostヘッダの値が使用されます。By default, Laravel will respond
to all requests it receives regardless of the
content of the HTTP request's Host
header. In addition, the Host header's
value will be used when generating absolute URLs to
your application during a web request.
通常、NginxやApacheなどのウェブサーバは、指定したホスト名と一致するリクエストだけをアプリケーションに送信するように設定する必要があります。しかし、Webサーバを直接カスタマイズする権限がなく、Laravelに特定のホスト名だけに応答するように指示する必要がある場合は、アプリケーションのミドルウェアIlluminate\Http\Middleware\TrustHostsを有効にすることで可能です。Typically, you should configure
your web server, such as Nginx or Apache, to only
send requests to your application that match a given
hostname. However, if you do not have the ability to
customize your web server directly and need to
instruct Laravel to only respond to certain
hostnames, you may do so by enabling the
Illuminate\Http\Middleware\TrustHosts
middleware for your application.
TrustHostsミドルウェアを有効にするには、アプリケーションのbootstrap/app.phpファイルで、trustHostsミドルウェアメソッドを呼び出す必要がある。このメソッドのat引数を使用して、アプリケーションが応答すべきホスト名を指定します。他のHostヘッダを持つリクエストは拒否します。To enable the
TrustHosts middleware, you should
invoke the trustHosts middleware method
in your application's bootstrap/app.php
file. Using the at argument of this
method, you may specify the hostnames that your
application should respond to. Incoming requests
with other Host headers will be
rejected:
->withMiddleware(function (Middleware $middleware) {
$middleware->trustHosts(at: ['laravel.test']);
})
デフォルトでは、アプリケーションのURLのサブドメインからのリクエストも自動的に信頼されます。この動作を無効にしたい場合は、subdomains引数を使います。By default, requests coming from
subdomains of the application's URL are also
automatically trusted. If you would like to disable
this behavior, you may use the
subdomains argument:
->withMiddleware(function (Middleware $middleware) {
$middleware->trustHosts(at: ['laravel.test'], subdomains: false);
})