リクエストの取得Accessing The Request
依存注入により、現在のHTTPリクエストインスタンスを取得するには、タイプヒントでIlluminate\Http\Request
クラスをコントローラーのコンストラクターかメソッドに指定します。現在のリクエストインスタンスが、サービスコンテナにより、自動的に注入されます。To obtain an instance of the
current HTTP request via dependency injection, you
should type-hint the
Illuminate\Http\Request
class on your
controller constructor or method. The current
request instance will automatically be injected by
the service
container[/docs/{{version}}/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');
//
}
}
もし、コントローラーメソッドでルートパラメーターも併用したい場合は、依存の指定の後にルート引数を続けてリストしてください。たとえば次のようにルートを定義している場合:If your controller method is also expecting input from a route parameter, simply list your route arguments after your other dependencies. For example, if your route is defined like so:
Route::put('user/{id}', 'UserController@update');
次のようにコントローラーメソッドの中で、まずタイプヒントでIlluminate\Http\Request
を指定し、それからルートパラメーターのid
へアクセスします。You may still type-hint the
Illuminate\Http\Request
and access your
route parameter id
by defining your
controller method like the following:
<?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)
{
//
}
}
基本のリクエスト情報Basic Request Information
Illuminate\Http\Request
インスタンスは、Symfony\Component\HttpFoundation\Request
クラスを拡張しており、HTTPリクエストを調べるために数多くのメソッドを提供しています。提供されている便利なメソッドをいくつか紹介しましょう。The
Illuminate\Http\Request
instance
provides a variety of methods for examining the HTTP
request for your application and extends the
Symfony\Component\HttpFoundation\Request
class. Here are a few more of the useful methods
available on this class:
リクエストURIの取得Retrieving The Request URI
path
メソッドはリクエストURIを返します。もしリクエストがhttp://domain.com/foo/bar
に送られたとすると、path
メソッドはfoo/bar
を返します。The path
method
returns the request's URI. So, if the incoming
request is targeted at
http://domain.com/foo/bar
, the
path
method will return
foo/bar
:
$uri = $request->path();
is
メソッドにより、リクエストのURIが指定されたパターンに合致するかを確認できます。このメソッドでは*
をワイルドカードとして使用できます。The is
method allows
you to verify that the incoming request URI matches
a given pattern. You may use the *
character as a wildcard when utilizing this
method:
if ($request->is('admin/*')) {
//
}
パス情報ではなく、完全なURLを取得したい場合は、リクエストインスタンスに対しurl
かfullUrl
メソッドを使用してください。To get the full URL, not just the
path info, you may use the url
or
fullUrl
methods on the request
instance:
// クエリ文字列なし
$url = $request->url();
// クエリ文字列付き
$url = $request->fullUrl();
クエリパラメータ付きのフルURLを取得することもできます。たとえば、リクエストのターゲットがhttp://domain.com/foo
の場合、次のメソッドはhttp://domain.com/foo?bar=baz
を返します。You may also get the full URL and
append query parameters. For example, if the request
is targeted at http://domain.com/foo
,
the following method will return
http://domain.com/foo?bar=baz
:
$url = $request->fullUrlWithQuery(['bar' => 'baz']);
リクエストメソッドの取得Retrieving The Request Method
method
メソッドはリクエストのHTTP動詞を返します。また、isMethod
メソッドを使えば、指定した文字列とHTTP動詞が一致するかを調べることができます。The method
method
will return the HTTP verb for the request. You may
also use the isMethod
method to verify
that the HTTP verb matches a given
string:
$method = $request->method();
if ($request->isMethod('post')) {
//
}
PSR-7リクエストPSR-7 Requests
PSR-7規約はリクエストとレスポンスを含めたHTTPメッセージのインターフェイスを規定しています。PSR-7リクエストのインスタンスを受け取りたければ、ライブラリーをいくつかインストールする必要があります。LaravelはLaravelリクエストとレスポンスをPSR-7互換の実装に変換するために、Symfony HTTPメッセージブリッジコンポーネントを使用しています。The PSR-7 standard specifies interfaces for HTTP messages, including requests and responses. If you would like to obtain an instance of a PSR-7 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 zendframework/zend-diactoros
ライブラリーをインストールしたら、後はただルートやコントローラーでリクエストタイプをタイプヒントで指定すれば、PSR-7リクエストが取得できます。Once you have installed these libraries, you may obtain a PSR-7 request by simply type-hinting the request type on your route or controller:
use Psr\Http\Message\ServerRequestInterface;
Route::get('/', function (ServerRequestInterface $request) {
//
});
ルートかコントローラーからPSR-7レスポンスインスタンスを返せば、自動的にLaravelのレスポンスインスタンスに変換され、フレームワークにより表示されます。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.
入力の取得Retrieving Input
入力値の取得Retrieving An Input Value
Illuminate\Http\Request
インスタンスのシンプルなメソッドを利用すれば、ユーザ入力の全てにアクセスできます。リクエストのHTTP動詞に気をもむ必要はありません。全ての動詞の入力に対し、同じ方法でアクセスできます。Using a few simple methods, you
may access all user input from your
Illuminate\Http\Request
instance. You
do not need to worry about the HTTP verb used for
the request, as input is accessed in the same way
for all verbs:
$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 on forms with array inputs, you may use "dot" notation to access the arrays:
$name = $request->input('products.0.name');
$names = $request->input('products.*.name');
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 dig deeper
into JSON arrays:
$name = $request->input('user.name');
入力値の存在チェックDetermining If An Input Value Is Present
リクエストに入力値が存在するかを調べるには、has
メソッドが使用できます。has
メソッドは値が存在し、かつ空文字ではない場合にtrue
を返します。To determine if a value is
present on the request, you may use the
has
method. The has
method
returns true
if the value is present
and is not an empty
string:
if ($request->has('name')) {
//
}
全入力データの取得Retrieving All Input Data
全入力を「配列」として受け取りたい場合は、all
メソッドを使用します。You may also retrieve all of the
input data as an array
using the
all
method:
$input = $request->all();
入力データの一部取得Retrieving A Portion Of The Input Data
入力データの一部を取得する必要があるなら、only
やexcept
メソッドが使用できます。両方のメソッドともに限定したい入力を「配列」や引数の並びとして指定します。If you need to retrieve a sub-set
of the input data, you may use the only
and except
methods. Both of these
methods will 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');
動的プロパティDynamic Properties
Illuminate\Http\Request
インスタンスに対する動的プロパティとして、ユーザインプットにアクセスすることも可能です。例えば、アプリケーションのフォーム上に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 posted field like so:
$name = $request->name;
動的プロパティが使われた場合、Laravelは最初にリクエスト本体のパラメータ値、次にルートパラメータを探します。When using dynamic properties, Laravel will first look for the parameter's value in the request payload and then in the route parameters.
直前の入力Old Input
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 services[/docs/{{version}}/validation], it is unlikely you will need to manually use these methods, 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
instance
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 sub-set of the request data into
the session:
$request->flashOnly(['username', 'email']);
$request->flashExcept('password');
入力をフラッシュデータとして保存しリダイレクトFlash Input Into Session Then Redirect
入力をフラッシュデータとして保存する必要があるのは、直前のページヘリダイレクトする場合が多いでしょうから、withInput
メソッドをリダイレクトにチェーンして簡単に、入力をフラッシュデータとして保存できます。Since you often will want to
flash input in association with a redirect to the
previous page, you may easily chain input flashing
onto a redirect using the withInput
method:
return redirect('form')->withInput();
return redirect('form')->withInput($request->except('password'));
直前のデータを取得Retrieving Old Data
直前のリクエストのフラッシュデータを取得するには、Request
インスタンスに対しold
メソッドを使用してください。old
メソッドはセッションにフラッシュデータとして保存されている入力を取り出すために役に立ちます。To retrieve flashed input from
the previous request, use the old
method on the Request
instance. The
old
method provides a convenient helper
for pulling the flashed input data out of the
session[/docs/{{version}}/session]:
$username = $request->old('username');
Laravelではold
ヘルパ関数も用意しています。特にBladeテンプレートで直前の入力値を表示したい場合に、old
ヘルパは便利です。指定した文字列の入力が存在していないときは、null
を返します。Laravel also provides a global
old
helper function. If you are
displaying old input within a Blade
template[/docs/{{version}}/blade], it is
more convenient to use the old
helper.
If no old input exists for the given string,
null
will be returned:
<input type="text" name="username" value="{{ old('username') }}">
クッキーCookies
リクエストからクッキーを取得Retrieving Cookies From The Request
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, you may
use the cookie
method on the
Illuminate\Http\Request
instance:
$value = $request->cookie('name');
レスポンスへ新しいクッキーを付けるAttaching A New Cookie To A Response
Laravelのグローバルcookie
ヘルパ関数は、新しいSymfony\Component\HttpFoundation\Cookie
インスタンスを生成する、シンプルなファクトリとして動作します。そのクッキーは、withCookie
メソッドを使用し、Illuminate\Http\Response
インスタンスに付けます。Laravel provides a global
cookie
helper function which serves as
a simple factory for generating new
Symfony\Component\HttpFoundation\Cookie
instances. The cookies may be attached to a
Illuminate\Http\Response
instance using
the withCookie
method:
$response = new Illuminate\Http\Response('Hello World');
$response->withCookie('name', 'value', $minutes);
return $response;
長期間有効、つまり最低5年間存在するクッキーを作成するには、cookie
ヘルパに引数を付けずに呼び出すことで返されるクッキーファクトリに対し、forever
メソッドをチェーンしてください。To create a long-lived cookie,
which lasts for five years, you may use the
forever
method on the cookie factory by
first calling the cookie
helper with no
arguments, and then chaining the
forever
method onto the returned cookie
factory:
$response->withCookie(cookie()->forever('name', 'value'));
ファイルFiles
アップロードファイルの取得Retrieving Uploaded Files
アップロードしたファイルへアクセスするには、Illuminate\Http\Request
インスタンスに含まれているfile
メソッドを使用します。file
メソッドにより返されるオブジェクトは、Symfony\Component\HttpFoundation\File\UploadedFile
クラスで、PHPのSplFileInfo
クラスを拡張しているので、ファイル操作のために数多くのメソッドが提供されています。You may access uploaded files
that are included with the
Illuminate\Http\Request
instance using
the file
method. The object returned by
the file
method is an instance of the
Symfony\Component\HttpFoundation\File\UploadedFile
class, which extends the PHP
SplFileInfo
class and provides a
variety of methods for interacting with the
file:
$file = $request->file('photo');
リクエスト中にファイルが存在しているかを判定するには、hadFile
メソッドを使います。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()) {
//
}
アップロードファイルの移動Moving Uploaded Files
アップロードしたファイルを別の場所へ移動するには、move
メソッドを使ってください。このメソッドはPHPの設定により決められるアップロード先の一時ディレクトリから、指定されたより長期間保存するための場所へファイルを移動します。To move the uploaded file to a
new location, you should use the move
method. This method will move the file from its
temporary upload location (as determined by your PHP
configuration) to a more permanent destination of
your choosing:
$request->file('photo')->move($destinationPath);
$request->file('photo')->move($destinationPath, $fileName);
他のファイルメソッドOther File Methods
他にも、たくさんのメソッドがUploadedFile
インスタンスに存在しています。このクラスのAPIドキュメントで、より詳細な情報が得られます。There are a variety of other
methods available on UploadedFile
instances. Check out the API documentation for
the
class[http://api.symfony.com/3.0/Symfony/Component/HttpFoundation/File/UploadedFile.html]
for more information regarding these
methods.