Readouble

Laravel 5.2 HTTPルーティング

基本的なルーティングBasic Routing

Laravelの全ルートは、フレームワークが自動的に読み込むapp/Http/routes.phpファイル中で定義されます。一番基本のLaravelルートはシンプルにURIと「クロージャ」により定義され、単純で記述しやすいルートの定義方法を提供しています。All Laravel routes are defined in the app/Http/routes.php file, which is automatically loaded by the framework. The most basic Laravel routes simply accept a URI and a Closure, providing a very simple and expressive method of defining routes:

Route::get('foo', function () {
    return 'Hello World';
});

デフォルトルート定義ファイルThe Default Routes File

デフォルトのroutes.phpファイルはRouteServiceProviderにより読み込まれ、セッションステータスへのアクセスとCSRF保護を提供するwebミドルウェアが自動的に適用されます。アプリケーションの殆どのルートは、このファイルで定義されるでしょう。The default routes.php file is loaded by the RouteServiceProvider and is automatically included in the web middleware group, which provides access to session state and CSRF protection. Most of the routes for your application will be defined within this file.

使用可能なルート定義メソッドAvailable Router Methods

ルータはHTTP動詞に対応してルートを定義できるようにしています。The router allows you to register routes that respond to any HTTP verb:

Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);

複数のHTTP動詞に対応したルートを登録する必要が起きることもあります。matchメソッドが利用できます。もしくは全HTTP動詞に対応するanyメソッドを使い、ルート登録することもできます。Sometimes you may need to register a route that responds to multiple HTTP verbs. You may do so using the match method. Or, you may even register a route that responds to all HTTP verbs using the any method:

Route::match(['get', 'post'], '/', function () {
    //
});

Route::any('foo', function () {
    //
});

ルートパラメーターRoute Parameters

必須パラメータRequired Parameters

もちろん、ルートの中のURIセグメントを取り出す必要が起きることもあります。たとえば、URLからユーザIDを取り出したい場合です。ルートパラメーターを定義してください。Of course, sometimes you will need to capture segments of the URI within your route. For example, you may need to capture a user's ID from the URL. You may do so by defining route parameters:

Route::get('user/{id}', function ($id) {
    return 'User '.$id;
});

ルートで必要なだけのルートパラメーターを定義することができます。You may define as many route parameters as required by your route:

Route::get('posts/{post}/comments/{comment}', function ($postId, $commentId) {
    //
});

ルートパラメーターは常に波括弧で囲います。パラメーターはそのルートが実行される時に「クロージャ」に渡されます。Route parameters are always encased within "curly" braces. The parameters will be passed into your route's Closure when the route is executed.

注意: ルートパラメーターは-文字を含むことができません。代わりに下線(_)を使ってください。Note: Route parameters cannot contain the - character. Use an underscore (_) instead.

任意パラメータOptional Parameters

ルートパラメータを指定してもらう必要があるが、指定は任意にしたいこともよく起こります。パラメータ名の後に?を付けると、任意指定のパラメータになります。対応するルートの引数に、デフォルト値を必ず付けてください。Occasionally you may need to specify a route parameter, but make the presence of that route parameter optional. You may do so by placing a ? mark after the parameter name. Make sure to give the route's corresponding variable a default value:

Route::get('user/{name?}', function ($name = null) {
    return $name;
});

Route::get('user/{name?}', function ($name = 'John') {
    return $name;
});

正規表現による限定Regular Expression Constraints

ルート定義でwhereを使用し、一致するルートパラメーターのフォーマットを限定することができます。whereメソッドはパラメーターの名前と、どのように限定するかを表す正規表現を引数に取ります。You may constrain the format of your route parameters using the where method on a route instance. The where method accepts the name of the parameter and a regular expression defining how the parameter should be constrained:

Route::get('user/{name}', function ($name) {
    //
})
->where('name', '[A-Za-z] ');

Route::get('user/{id}', function ($id) {
    //
})
->where('id', '[0-9] ');

Route::get('user/{id}/{name}', function ($id, $name) {
    //
})
->where(['id' => '[0-9] ', 'name' => '[a-z] ']);

グローバルな限定Global Constraints

ある名前のルートパラメーターをいつも正規表現で限定したい場合は、patternメソッドを使用してください。RouteServiceProviderbootメソッドでこうしたパターンを定義してください。If you would like a route parameter to always be constrained by a given regular expression, you may use the pattern method. You should define these patterns in the boot method of your RouteServiceProvider:

/**
 * ルートモデルの結合、パターンフィルタなどの定義
 *
 * @param  \Illuminate\Routing\Router  $router
 * @return void
 */
public function boot(Router $router)
{
    $router->pattern('id', '[0-9] ');

    parent::boot($router);
}

パターンを一度定義すれば、そのパラメーター名を使用している全ルートで自動的に適用されます。Once the pattern has been defined, it is automatically applied to all routes using that parameter name:

Route::get('user/{id}', function ($id) {
    // Only called if {id} is numeric.
});

名前付きルートNamed Routes

名前付きルートは特定のルートへのURLを生成したり、リダイレクトしたりする場合に便利です。ルートを定義するときに、as配列キーを使用して名前を指定してください。Named routes allow the convenient generation of URLs or redirects for specific routes. You may specify a name for a route using the as array key when defining the route:

Route::get('user/profile', ['as' => 'profile', function () {
    //
}]);

コントローラーアクションに対しても名前を付けることができます。You may also specify route names for controller actions:

Route::get('user/profile', [
    'as' => 'profile', 'uses' => 'UserController@showProfile'
]);

ルート定義の配列の中でルート名を指定する代わりに、ルート定義の最後にnameメソッドをつなげることもできます。Alternatively, instead of specifying the route name in the route array definition, you may chain the name method onto the end of the route definition:

Route::get('user/profile', 'UserController@showProfile')->name('profile');

ルートグループと名前付きルートRoute Groups & Named Routes

ルートグループを使用している場合、ルートグループの属性配列でasキーワードを指定し、グループ内の全ルートに共通な名前のプリフィックスを指定することができます。If you are using route groups[#route-groups], you may specify an as keyword in the route group attribute array, allowing you to set a common route name prefix for all routes within the group:

Route::group(['as' => 'admin::'], function () {
    Route::get('dashboard', ['as' => 'dashboard', function () {
        // Route named "admin::dashboard"
    }]);
});

名前付きルートへのURLを生成するGenerating URLs To Named Routes

ルートに一度名前を付ければ、その名前をグローバルなroute関数で使用することで、URLを生成したり、リダイレクトしたりできます。Once you have assigned a name to a given route, you may use the route's name when generating URLs or redirects via the global route function:

// URLの生成
$url = route('profile');

// リダイレクトの生成
return redirect()->route('profile');

そのルートでパラメーターを定義してある場合は、route関数の第2引数としてパラメーターを渡してください。指定されたパラメーターは自動的にURLの正しい場所へ埋め込まれます。If the named route defines parameters, you may pass the parameters as the second argument to the route function. The given parameters will automatically be inserted into the URL in their correct positions:

Route::get('user/{id}/profile', ['as' => 'profile', function ($id) {
    //
}]);

$url = route('profile', ['id' => 1]);

ルートグループRoute Groups

ルートグループは多くのルートで共通なミドルウェアや名前空間のようなルート属性をルートごとに定義するのではなく、一括して適用するための手法です。Route::groupメソッドの最初の引数には、共通の属性を配列で指定します。Route groups allow you to share route attributes, such as middleware or namespaces, across a large number of routes without needing to define those attributes on each individual route. Shared attributes are specified in an array format as the first parameter to the Route::group method.

ルートグループについてより理解を深めるために、この機能の一般的なユースケースを学んでください。To learn more about route groups, we'll walk through several common use-cases for the feature.

ミドルウェアMiddleware

グループの中の全ルートにミドルウェアを指定するには、middlewareキーをグループ属性配列に使用します。この配列で指定した順番にミドルウェアは実行されます。To assign middleware to all routes within a group, you may use the middleware key in the group attribute array. Middleware will be executed in the order you define this array:

Route::group(['middleware' => 'auth'], function () {
    Route::get('/', function ()    {
        // Authミドルウェアを使用
    });

    Route::get('user/profile', function () {
        // Authミドルウェアを使用
    });
});

名前空間Namespaces

ルートグループのもう一つのよくあるユースケースは、グループ内のコントローラーに同じPHP名前空間を指定する場合です。グループ中の全コントローラーに対して適用する名前空間をグループ属性配列のnamespaceキーを使用し指定します。Another common use-case for route groups is assigning the same PHP namespace to a group of controllers. You may use the namespace parameter in your group attribute array to specify the namespace for all controllers within the group:

Route::group(['namespace' => 'Admin'], function()
{
    // "App\Http\Controllers\Admin"名前空間下のコントローラ

    Route::group(['namespace' => 'User'], function() {
        // "App\Http\Controllers\Admin\User"下のコントローラ
    });
});

App\Http\Controllers名前空間をコントローラールート登録時に毎回指定しなくても済むように、デフォルトでRouteServiceProviderが名前空間グループの中でroutes.phpファイルを読み込み、指定していることを覚えておいてください。これにより、先頭のApp\Http\Controllers名前空間を省略でき、続きの部分を指定するだけで済みます。Remember, by default, the RouteServiceProvider includes your routes.php file within a namespace group, allowing you to register controller routes without specifying the full App\Http\Controllers namespace prefix. So, we only need to specify the portion of the namespace that comes after the base App\Http\Controllers namespace.

サブドメインルーティングSub-Domain Routing

ルートグループはワイルドカードサブドメインをルート定義するためにも使えます。サブドメインの部分を取り出しルートやコントローラーで使用するために、ルートURIにおけるルートパラメーターのように指定できます。サブドメインはグループ属性配列でdomainキーにより指定します。Route groups may also be used to route wildcard sub-domains. Sub-domains may be assigned route parameters just like route URIs, allowing you to capture a portion of the sub-domain for usage in your route or controller. The sub-domain may be specified using the domain key on the group attribute array:

Route::group(['domain' => '{account}.myapp.com'], function () {
    Route::get('user/{id}', function ($account, $id) {
        //
    });
});

ルートプレフィックスRoute Prefixes

prefixグループ配列属性はグループ内の各ルートに対して、指定されたURIのプレフィックスを指定するために使用します。たとえばグループ内の全ルートのURIにadminを付けたければ、次のように指定します。The prefix group attribute may be used to prefix each route in the group with a given URI. For example, you may want to prefix all route URIs within the group with admin:

Route::group(['prefix' => 'admin'], function () {
    Route::get('users', function ()    {
        // "/admin/users"のURIと一致
    });
});

prefixパラメーターは、グループ内のルートに対して、共通のパラメーターを指定するためにも使用できます。You may also use the prefix parameter to specify common parameters for your grouped routes:

Route::group(['prefix' => 'accounts/{account_id}'], function () {
    Route::get('detail', function ($accountId)    {
        // "/accounts/{account_id}/detail"のURLと一致
    });
});

CSRF保護CSRF Protection

イントロダクションIntroduction

Laravelでは、クロス・サイト・リクエスト・フォージェリ(CSRF)からアプリケーションを簡単に守れます。クロス・サイト・リクエスト・フォージェリは悪意のあるエクスプロイトの一種であり、信頼できるユーザーになり代わり、認められていないコマンドを実行します。Laravel makes it easy to protect your application from cross-site request forgery[http://en.wikipedia.org/wiki/Cross-site_request_forgery] (CSRF) attacks. Cross-site request forgeries are a type of malicious exploit whereby unauthorized commands are performed on behalf of an authenticated user.

Laravelは、アプリケーションにより管理されているアクティブなユーザーの各セッションごとに、CSRF「トークン」を自動的に生成しています。このトークンを認証済みのユーザーが、実装にアプリケーションに対してリクエストを送信しているのかを確認するために利用します。Laravel automatically generates a CSRF "token" for each active user session managed by the application. This token is used to verify that the authenticated user is the one actually making the requests to the application.

アプリケーションでHTMLフォームを定義する場合はいつでも、隠しCSRFトークンフィールドをフォームに埋め込み、CSRF保護ミドルウェアがリクエストの有効性をチェックできるようにしなければなりません。CSRFトークンを含んだ、_token隠し入力フィールドを生成するには、csrf_fieldヘルパ関数を使ってください。Anytime you define a HTML form in your application, you should include a hidden CSRF token field in the form so that the CSRF protection middleware will be able to validate the request. To generate a hidden input field _token containing the CSRF token, you may use the csrf_field helper function:

// 通常のPHPコード
<?php echo csrf_field(); ?>

// Bladeテンプレート記法
{{ csrf_field() }}

csrf_fieldヘルパは、以下のHTMLを生成します。The csrf_field helper function generates the following HTML:

<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">

POST、PUT、DELETEリクエストのCSRFトークンを自分で確認する必要はありません。webミドルウェアグループに含まれている、VerifyCsrfToken ミドルウェアが、リクエスト中のトークンとセッションに保存されているトークンが一致するか、確認しています。You do not need to manually verify the CSRF token on POST, PUT, or DELETE requests. The VerifyCsrfToken middleware[/docs/{{version}}/middleware], which is included in the web middleware group, will automatically verify that the token in the request input matches the token stored in the session.

CSRF保護から特定URIを除外Excluding URIs From CSRF Protection

一連のURIをCSRF保護より除外したい場合もあります。たとえば、Stripeを料金の受け取りに採用しており、そのWebフックシステムを利用している時は、LaravelのCSRF保護よりWebフック処理ルートを除外する必要があるでしょう。Sometimes you may wish to exclude a set of URIs from CSRF protection. For example, if you are using Stripe[https://stripe.com] to process payments and are utilizing their webhook system, you will need to exclude your webhook handler route from Laravel's CSRF protection.

デフォルトのroutes.phpファイルで適用されるwebミドルウェアグループ外で除外URIを定義するか、もしくはVerifyCsrfTokenミドルウェアの$exceptプロパティにそのURIを追加してください。You may exclude URIs by defining their routes outside of the web middleware group that is included in the default routes.php file, or by adding the URIs to the $except property of the VerifyCsrfToken middleware:

<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier
{
    /**
     * CSRFバリデーションから除外するURI
     *
     * @var array
     */
    protected $except = [
        'stripe/*',
    ];
}

X-CSRF-TOKENX-CSRF-TOKEN

更に追加でPOSTパラメーターとしてCSRFトークンを確認したい場合は、LaravelのVerifyCsrfTokenミドルウェアがX-CSRF-TOKENリクエストヘッダもチェックします。たとえば、"meta"タグにトークンを保存します。In addition to checking for the CSRF token as a POST parameter, the Laravel VerifyCsrfToken middleware will also check for the X-CSRF-TOKEN request header. You could, for example, store the token in a "meta" tag:

<meta name="csrf-token" content="{{ csrf_token() }}">

metaタグを作成したら、jQueryのようなライブラリーで、全リクエストヘッダにトークンを追加できます。この手法によりAJAXベースのアプリケーションにシンプルで便利なCSRF保護を提供できます。Once you have created the meta tag, you can instruct a library like jQuery to add the token to all request headers. This provides simple, convenient CSRF protection for your AJAX based applications:

$.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
});

X-XSRF-TOKENX-XSRF-TOKEN

Laravelは更にCSRFトークンをXSRF-TOKENクッキーの中に保存します。このクッキーの値をX-XSRF-TOKENリクエストヘッダにセットすることが可能です。AngularのようなJavaScriptフレームワークでは、自動的に行われます。自動で行われない場合は、手動で値を設定する必要があります。Laravel also stores the CSRF token in a XSRF-TOKEN cookie. You can use the cookie value to set the X-XSRF-TOKEN request header. Some JavaScript frameworks, like Angular, do this automatically for you. It is unlikely that you will need to use this value manually.

モデル結合ルートRoute Model Binding

Laravelのモデル結合ルートはルートへモデルインスタンスを依存注入する便利な手法です。たとえば、ユーザのIDを受け取る代わりに、指定されたIDと一致するUserモデルインスタンスそのものを依存注入で受け取れます。Laravel route model binding provides a convenient way to inject model instances into your routes. For example, instead of injecting a user's ID, you can inject the entire User model instance that matches the given ID.

暗黙の結合Implicit Binding

Laravelは変数名とルートセグメント名が一致する場合、LaravelはルートかコントローラアクションでEloquentモデルが定義されていると、自動的に依存解決します。Laravel will automatically resolve type-hinted Eloquent models defined in routes or controller actions whose variable names match a route segment name. For example:

Route::get('api/users/{user}', function (App\User $user) {
    return $user->email;
});

この例では、Eloquentをタイプヒントしているルート上の$user変数が、ルートURIの{user}セグメントと名前が一致しているので、LaravelはリクエストURI上の対応するIDを持つ、モデルインスタンスを自動的に依存注入します。In this example, since the Eloquent type-hinted $user variable defined on the route matches the {user} segment in the route's URI, Laravel will automatically inject the model instance that has an ID matching the corresponding value from the request URI.

一致するモデルインスタンスがデータベース上に見つからない場合、404 HTTPレスポンスが自動的に生成されます。If a matching model instance is not found in the database, a 404 HTTP response will be automatically generated.

キー名のカスタマイズCustomizing The Key Name

モデル取得時にid以外のデータベースカラムを暗黙のモデル結合で使用したい場合、EloquentモデルのgetRouteKeyNameメソッドをオーバーライドしてください。If you would like the implicit model binding to use a database column other than id when retrieving models, you may override the getRouteKeyName method on your Eloquent model:

/**
 * モデルのルートキーの取得
 *
 * @return string
 */
public function getRouteKeyName()
{
    return 'slug';
}

明白な結合Explicit Binding

明白な結合を登録するときは、指定したパラメータに対するクラスをルータのmodelメソッドにより登録します。モデルの結合は、RouteServiceProvider::bootメソッドで定義します。To register an explicit binding, use the router's model method to specify the class for a given parameter. You should define your model bindings in the RouteServiceProvider::boot method:

引数をモデルに結合するBinding A Parameter To A Model

public function boot(Router $router)
{
    parent::boot($router);

    $router->model('user', 'App\User');
}

次に{user}パラメーターを含むルートを定義します。Next, define a route that contains a {user} parameter:

$router->get('profile/{user}', function(App\User $user) {
    //
});

{user}パラメーターをApp\Userモデルへ結合しているため、Userインスタンスはルートへ注入されます。ですからたとえば、profile/1のリクエストでは、IDが1のインスタンスが注入されます。Since we have bound the {user} parameter to the App\User model, a User instance will be injected into the route. So, for example, a request to profile/1 will inject the User instance which has an ID of 1.

一致するモデルインスタンスがデータベース上に見つからない場合、404 HTTPレスポンスが自動的に生成されます。If a matching model instance is not found in the database, a 404 HTTP response will be automatically generated.

依存解決ロジックのカスタマイズCustomizing The Resolution Logic

独自の依存解決ロジックを使いたい場合は、Route::bindメソッドを使います。bindメソッドに渡す「クロージャ」は、URIセグメントの値を受け取るので、ルートへ注入したいクラスのインスタンスを返してください。If you wish to use your own resolution logic, you should use the Route::bind method. The Closure you pass to the bind method will receive the value of the URI segment, and should return an instance of the class you want to be injected into the route:

$router->bind('user', function ($value) {
    return App\User::where('name', $value)->first();
});

"Not Found"時の振る舞いのカスタマイズCustomizing The "Not Found" Behavior

独自の"Not Found"時の動作を指定したいときは、modelメソッドの第3引数に「クロージャ」を渡してください。If you wish to specify your own "not found" behavior, pass a Closure as the third argument to the model method:

$router->model('user', 'App\User', function () {
    throw new NotFoundHttpException;
});

擬似フォームメソッドForm Method Spoofing

HTLMフォームはPUTPATCHDELETEアクションをサポートしていません。ですから、HTMLフォームから呼ばれるPUTPATCHDELETEルートを定義する時、フォームに_method隠しフィールドを追加する必要があります。_methodフィールドとして送られた値は、HTTPリクエストメソッドとして使用されます。HTML forms do not support PUT, PATCH or DELETE actions. So, when defining PUT, PATCH or DELETE routes that are called from an HTML form, you will need to add a hidden _method field to the form. The value sent with the _method field will be used as the HTTP request method:

<form action="/foo/bar" method="POST">
    <input type="hidden" name="_method" value="PUT">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>

_method隠し入力フィールドを生成するために、method_fieldヘルパ関数を使用することもできます。To generate the hidden input field _method, you may also use the method_field helper function:

<?php echo method_field('PUT'); ?>

もちろん、Bladeテンプレートエンジンを使用できます。Of course, using the Blade templating engine[/docs/{{version}}/blade]:

{{ method_field('PUT') }}

現在のルートへのアクセスAccessing The Current Route

Route::current()メソッドは、現在のHTTPリクエストを処理しているルートを返します。これはIlluminate\Routing\Routeインスタンスで、メソッドによりルートの情報を調べることができます。The Route::current() method will return the route handling the current HTTP request, allowing you to inspect the full Illuminate\Routing\Route instance:

$route = Route::current();

$name = $route->getName();

$actionName = $route->getActionName();

RouteファサードのcurrentRouteNamecurrentRouteActionヘルパメソッドも使用でき、現在のルートの名前とアクションへアクセスできます。You may also use the currentRouteName and currentRouteAction helper methods on the Route facade to access the current route's name or action:

$name = Route::currentRouteName();

$action = Route::currentRouteAction();

組み込まれている全メソッドを確認するには、Routeファサードの裏で動作しているクラスと、Routeインスタンスの2つについてのAPIドキュメントを参照してください。Please refer to the API documentation for both the underlying class of the Route facade[http://laravel.com/api/{{version}}/Illuminate/Routing/Router.html] and Route instance[http://laravel.com/api/{{version}}/Illuminate/Routing/Route.html] to review all accessible methods.

章選択

設定

明暗テーマ
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!…]形式の挿入削除行の表示形式です。

テストコード表示
両コード表示
Pestのみ表示
PHPUnitのみ表示
和文変換

対象文字列と置換文字列を半角スペースで区切ってください。(最大5組各10文字まで)

本文フォント

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

コードフォント

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

保存内容リセット

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

ヘッダー項目移動

キーボード操作