基本的なルーティングBasic Routing
アプリケーションのほとんどのルートは、app/Http/routes.php
ファイルの中で定義することになります。このファイルは、App\Providers\RouteServiceProvider
クラスによりロードされています。一番基本的なLaravelのルートは、URIと「クロージャー」を指定します。You will define most of the
routes for your application in the
app/Http/routes.php
file, which is
loaded by the
App\Providers\RouteServiceProvider
class. The most basic Laravel routes simply accept a
URI and a Closure
:
Route::get('/', function () {
return 'Hello World';
});
Route::post('foo/bar', function () {
return 'Hello World';
});
Route::put('foo/bar', function () {
//
});
Route::delete('foo/bar', function () {
//
});
複数のHTTP動詞に対応するルートの登録Registering A Route For Multiple Verbs
複数のHTTP動詞に対応するルートを登録する必要が時々起きます。Route
ファサードのmatch
メソッドを使用してください。Sometimes you may need to
register a route that responds to multiple HTTP
verbs. You may do so using the match
method on the Route
facade[/docs/{{version}}/facades]:
Route::match(['get', 'post'], '/', function () {
return 'Hello World';
});
もしくは全HTTP動詞に対応するany
メソッドを使い、ルート登録することもできます。Or, you may even register a route
that responds to all HTTP verbs using the
any
method:
Route::any('foo', function () {
return 'Hello World';
});
ルートに対応するURLの生成Generating URLs To Routes
アプリケーションのルートに対するURLを生成するには、url
ヘルパを使ってください。You may generate URLs to your
application's routes using the url
helper:
$url = url('foo');
ルートパラメーター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:
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) {
// {id}が数値の場合のみ呼び出される
});
名前付きルートNamed Routes
名前付きルートは特定のルートへのURLを生成したり、リダイレクトしたりする場合に便利です。ルートを定義するときに、as
配列キーを使用して名前を指定してください。Named routes allow you to
conveniently generate URLs or redirects for a
specific route. 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
メソッドをつなげることもできます。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 () {
// ルート名は"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
route
function:
$url = route('profile');
$redirect = redirect()->route('profile');
そのルートでパラメーターを定義してある場合は、route
メソッドの第2引数としてパラメーターを渡してください。指定されたパラメーターは自動的にURLへ埋め込まれます。If the route defines parameters,
you may pass the parameters as the second argument
to the route
method. The given
parameters will automatically be inserted into the
URL:
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
root.
サブドメインルーティング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
array 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" URLに一致
});
});
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 ($account_id) {
// "accounts/{account_id}/detail" URLに一致
});
});
CSRF保護CSRF Protection
イントロダクションIntroduction
Laravelでは、クロス・サイト・リクエスト・フォージェリからアプリケーションを簡単に守れます。クロス・サイト・リクエスト・フォージェリは悪意のあるエクスプロイトの一種であり、信頼できるユーザーになり代わり、認められていないコマンドを実行します。Laravel makes it easy to protect your application from cross-site request forgeries[http://en.wikipedia.org/wiki/Cross-site_request_forgery]. Cross-site request forgeries are a type of malicious exploit whereby unauthorized commands are performed on behalf of the authenticated user.
Laravelは、アプリケーションにより管理されているアクティブなユーザーの各セッションごとに、CSRF「トークン」を自動的に生成しています。このトークンは認証済みのユーザーが、実装にアプリケーションに対してリクエストを送信しているのかを確認するために利用します。CSRFトークンを含む_token
隠し入力フィールドを生成するには、csrf_field
ヘルパ関数が使用できます。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. To
generate a hidden input field _token
containing the CSRF token, you may use the
csrf_field
helper function:
<?php echo csrf_field(); ?>
csrf_field
ヘルパは、以下のHTMLを生成します。The csrf_field
helper function generates the following
HTML:
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
もちろん、Bladeテンプレートエンジンを使用できます。Of course, using the Blade templating engine[/docs/{{version}}/blade]:
{{ csrf_field() }}
POST、PUT、DELETEリクエストのCSRFトークンを自分で確認する必要はありません。VerifyCsrfToken
HTTPミドルウェアが、リクエスト中のトークンとセッションに保存されているトークンが一致するか、確認しています。You do not need to manually
verify the CSRF token on POST, PUT, or DELETE
requests. The VerifyCsrfToken
HTTP
middleware[/docs/{{version}}/middleware]
will 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.
VerifyCsrfToken
ミドルウェアの$except
プロパティに除外URIを追加してください。You may exclude URIs by adding
them 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 class instances
into your routes. For example, instead of injecting
a user's ID, you can inject the entire
User
class instance that matches the
given ID.
最初にルーターのmodel
メソッドで指定されたパラメーターに対するクラスを指定します。RouteServiceProvider::boot
メソッドでモデル結合を定義してください。First, 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例外が投げられます。Note: If a matching model instance is not found in the database, a 404 exception will be thrown automatically.
独自の「見つかりません」動作を指定したい場合は、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;
});
独自の依存解決ロジックを使いたい場合は、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();
});
見せかけのフォームメソッド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') }}
404エラーのthrowThrowing 404 Errors
手動で404エラーをルートから発生させるには2つの手法があります。最初の方法はabort
ヘルパを使用する方法です。abort
ヘルパは、Symfony\Component\HttpFoundation\Exception\HttpException
例外を指定したステータスコードと共に投げる(throw)だけです。There are two ways to manually
trigger a 404 error from a route. First, you may use
the abort
helper. The
abort
helper simply throws a
Symfony\Component\HttpFoundation\Exception\HttpException
with the specified status code:
abort(404);
2つめの方法はSymfony\Component\HttpKernel\Exception\NotFoundHttpException
のインスタンスを投げる方法です。Secondly, you may manually throw
an instance of
Symfony\Component\HttpKernel\Exception\NotFoundHttpException
.
404例外の取り扱いやエラーのカスタム処理を行う詳しい方法は、ドキュメントのエラーの章をご覧ください。More information on handling 404 exceptions and using custom responses for these errors may be found in the errors[/docs/{{version}}/errors#http-exceptions] section of the documentation.