基本的なルーティング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
メソッドを使用してください。RouteServiceProvider
のboot
メソッドでこうしたパターンを定義してください。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フォームはPUT
、PATCH
、DELETE
アクションをサポートしていません。ですから、HTMLフォームから呼ばれるPUT
、PATCH
、DELETE
ルートを定義する時、フォームに_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
ファサードのcurrentRouteName
とcurrentRouteAction
ヘルパメソッドも使用でき、現在のルートの名前とアクションへアクセスできます。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.