Readouble

Laravel master HTTPリクエスト

リクエストの取得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 method. The incoming 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');

        //
    }
}

依存注入とルートパラメータDependency Injection & 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:

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 as follows:

<?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)
    {
        //
    }
}

リクエストの取得 Via Route ClosuresAccessing The Request Via Route Closures

ルートクロージャでもIlluminate\Http\Requesをタイプヒントで指定できます。そのルートが実行されると、送信されてきたリクエストをサービスコンテナが自動的にクロージャへ渡します。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) {
    //
});

リクエストパスとメソッドRequest Path & Method

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. We will discuss a few of the most important methods below.

リクエストURIの取得Retrieving The Request Path

pathメソッドはリクエストURIを返します。もしリクエストがhttp://domain.com/foo/barに送られたとすると、pathメソッドはfoo/barを返します。The path method returns the request's path information. 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 path matches a given pattern. You may use the * character as a wildcard when utilizing this method:

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

リクエストURLの取得Retrieving The Request URL

送信されたリクエストの完全なURLを取得する場合は、urlfullUrlメソッドを使用してください。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();

// クエリ文字列付き
$url = $request->fullUrl();

リクエストメソッドの取得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')) {
    //
}

PSR-7リクエストPSR-7 Requests

PSR-7規約はリクエストとレスポンスを含めたHTTPメッセージのインターフェイスを規定しています。PSR-7リクエストのインスタンスを受け取りたければ、ライブラリーをいくつかインストールする必要があります。LaravelはLaravelリクエストとレスポンスをPSR-7互換の実装に変換するために、Symfony HTTPメッセージブリッジコンポーネントを使用しています。The PSR-7 standard[http://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 zendframework/zend-diactoros

これらのライブラリをインストールし、ルートクロージャかコントローラメソッドで、リクエストインターフェイスをタイプヒントで指定すれば、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) {
    //
});

lightbulb">Tip!! ルートかコントローラーからPSR-7レスポンスインスタンスを返せば、自動的にLaravelのレスポンスインスタンスに変換され、フレームワークにより表示されます。{tip} 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 All Input Data

全入力を「配列」として受け取りたい場合は、allメソッドを使用します。You may also retrieve all of the input data as an array using the all method:

$input = $request->all();

入力値の取得Retrieving An Input Value

Illuminate\Http\Requestインスタンスのシンプルなメソッドを利用すれば、ユーザ入力の全てにアクセスできます。リクエストのHTTP動詞に気をもむ必要はありません。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');

入力の取得 Via Dynamic PropertiesRetrieving Input Via 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 field like so:

$name = $request->name;

動的プロパティが使われた場合、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 route parameters.

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 into JSON arrays:

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

入力データの一部取得Retrieving A Portion Of The Input Data

入力データの一部を取得する必要があるなら、onlyexceptメソッドが使用できます。両方のメソッドともに限定したい入力を「配列」や引数の並びとして指定します。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');

入力値の存在チェックDetermining If An Input Value Is Present

リクエストに入力値が存在するかを調べるには、hasメソッドが使用できます。hasメソッドは値が存在し、かつ空文字ではない場合にtrueを返します。You should use the has method to determine if a value is present on the request. The has method returns true if the value is present and is not an empty string:

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

直前の入力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 features[/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 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();

セッションへ入力の一部をフラッシュデータとして保存するには、flashOnlyflashExceptが使用できます。両メソッドは、パスワードなどの機密情報をセッションに含めないために便利です。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('form')->withInput(
    $request->except('password')
);

直前のデータを取得Retrieving Old Input

直前のリクエストのフラッシュデータを取得するには、Requestインスタンスに対しoldメソッドを使用してください。oldメソッドはセッションにフラッシュデータとして保存されている入力を取り出すために役に立ちます。To retrieve flashed input from the previous request, use the old method on the Request instance. 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. 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 a Illuminate\Http\Request instance:

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

レスポンスへクッキーを付けるAttaching Cookies To Responses

送信するIlluminate\Http\Responseインスタンスへcookieメソッドを使い、クッキーを付加できます。このメソッドには、名前、値、それとこのクッキーが有効である分数を渡します。You may attach a cookie to an outgoing Illuminate\Http\Response instance using the cookie method. You should pass the name, value, and number of minutes the cookie should be considered valid to this method:

return response('Hello World')->cookie(
    'name', 'value', $minutes
);

cookieメソッドには、あまり繁用されない、いくつかの引数を付けることもできます。そうした引数は、PHPネイティブのsetcookieメソッドの引数と、全般的に同じ目的や意味合いを持っています。The cookie method also accepts a few more arguments which are used less frequently. Generally, these arguments have the same purpose and meaning as the arguments that would be given to PHP's native setcookie[http://php.net/manual/en/function.setcookie.php] method:

return response('Hello World')->cookie(
    'name', 'value', $minutes, $path, $domain, $secure, $httpOnly
);

Cookieインスタンスの生成Generating Cookie Instances

後からレスポンスインスタンスへ付けることが可能な、Symfony\Component\HttpFoundation\Cookieインスタンスを生成したければ、cookieグローバルヘルパが使えます。このクッキーはレスポンスインスタンスへアタッチしない限り、クライアントへ送信されません。If you would like to generate a Symfony\Component\HttpFoundation\Cookie instance that can be given to a response instance at a later time, you may use the global cookie helper. This cookie will not be sent back to the client unless it is attached to a response instance:

$cookie = cookie('name', 'value', $minutes);

return response('Hello World')->cookie($cookie);

ファイルFiles

アップロードファイルの取得Retrieving Uploaded Files

アップロードしたファイルへアクセスするには、Illuminate\Http\Requestインスタンスに含まれているfileメソッドか、動的プロパティを使用します。fileメソッドはIlluminate\Http\UploadedFileクラスのインスタンスを返します。これはPHPのSplFileInfoクラスを拡張してあり、様々なファイル操作のメソッドを提供しています。You may access uploaded files from a 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;

リクエスト中にファイルが存在しているかを判定するには、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()) {
    //
}

ファイルパスと拡張子File Paths & 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[http://api.symfony.com/3.0/Symfony/Component/HttpFoundation/File/UploadedFile.html] for more information regarding these methods.

アップロードファイルの保存Storing Uploaded Files

アップロードファイルを保存するには、通常設定済みのファイルシステムの1つを使います。UploadedFileクラスのstoreメソッドは、ローカルにあろうが、Amazon S3のようなクラウドストレージであろうが、ディスクの1つへアップロードファイルを移動します。To store an uploaded file, you will typically use one of your configured filesystems[/docs/{{version}}/filesystem]. The UploadedFile class has a store method which will move an uploaded file to one of your disks, which may be a location on your local filesystem or even a cloud storage location like Amazon S3.

storeメソッドへは、ファイルシステムで設定したルートディレクトリからの相対位置で、どこに保存するか指定します。このパスにはファイル名を含んではいけません。ファイルの内容のMD5ハッシュを使い、自動的に名前が生成されるためです。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 file name, since the name will automatically be generated using the MD5 hash of the file's contents.

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 file name to be automatically generated, you may use the storeAs method, which accepts the path, file name, and disk name as its arguments:

$path = $request->photo->storeAs('images', 'filename.jpg');

$path = $request->photo->storeAs('images', 'filename.jpg', 's3');

章選択

開発環境
ビューとテンプレート
公式パッケージ

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作