基本的なルーティングBasic Routing
一番基本のLaravelルートはシンプルにURIと「クロージャ」により定義され、単純で記述しやすいルートの定義方法を提供しています。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 Route Files
Laravelの全ルートは、routes
ディレクトリ下に設置されている、ルートファイルで定義されます。これらのファイルはフレームワークにより、自動的に読み込まれます。routes/web.php
ファイルで、Webインターフェイスのルートを定義します。定義されたルートはweb
ミドルウェアグループにアサインされ、セッション状態やCSRF保護などの機能が提供されます。routes/api.php
中のルートはステートレスで、api
ミドルウェアグループにアサインされます。All Laravel routes are defined in
your route files, which are located in the
routes
directory. These files are
automatically loaded by the framework. The
routes/web.php
file defines routes that
are for your web interface. These routes are
assigned the web
middleware group,
which provides features like session state and CSRF
protection. The routes in
routes/api.php
are stateless and are
assigned the api
middleware
group.
ほとんどのアプリケーションでは、routes/web.php
のルート定義から始めることになるでしょう。For most applications, you will
begin by defining routes in your
routes/web.php
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 () {
//
});
CSRF保護CSRF Protection
web
ルートファイル中で定義され、POST
、PUT
、DELETE
ルートへ送信されるHTMLフォームはすべて、CSRFトークンフィールドを含んでいる必要があります。含めていないと、そのリクエストは拒否されます。CSRF保護についての詳細は、CSRFのドキュメントをご覧ください。Any HTML forms pointing to
POST
, PUT
, or
DELETE
routes that are defined in the
web
routes file should include a CSRF
token field. Otherwise, the request will be
rejected. You can read more about CSRF protection in
the CSRF
documentation[/docs/{{version}}/csrf]:
<form method="POST" action="/profile">
{{ csrf_field() }}
...
</form>
ルートパラメーター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 {}
braces and should
consist of alphabetic characters, and may not
contain a -
character. Instead of using
the -
character, use an underscore
(_
) instead. Route parameters are
injected into route callbacks / controllers based on
their order - the names of the callback / controller
arguments do not matter.
任意パラメータ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
:
/**
* ルートモデル結合、パターンフィルタなどの定義
*
* @return void
*/
public function boot()
{
Route::pattern('id', '[0-9] ');
parent::boot();
}
パターンを定義すると、パラメータ名を使用している全ルートで、自動的に提供されます。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を生成したり、リダイレクトしたりする場合に便利です。ルート定義にname
メソッドをチェーンすることで、そのルートに名前がつけられます。Named routes allow the convenient
generation of URLs or redirects for specific routes.
You may specify a name for a route by chaining the
name
method onto the route
definition:
Route::get('user/profile', function () {
//
})->name('profile');
コントローラーアクションに対しても名前を付けることができます。You may also specify route names for controller actions:
Route::get('user/profile', 'UserController@showProfile')->name('profile');
名前付きルートへの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', function ($id) {
//
})->name('profile');
$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.
ミドルウェアMiddleware
グループ中の全ルートにミドルウェアを指定するには、そのグループを定義する前にmiddleware
メソッドを使用します。ミドルウェアは、配列に定義された順番で実行されます。To assign middleware to all
routes within a group, you may use the
middleware
method before defining the
group. Middleware are executed in the order they are
listed in the array:
Route::middleware(['first', 'second'])->group(function () {
Route::get('/', function () {
// firstとsecondミドルウェアを使用
});
Route::get('user/profile', function () {
// firstとsecondミドルウェアを使用
});
});
名前空間Namespaces
ルートグループのもう一つのよくあるユースケースで、グループ内のコントローラーに同じPHP名前空間を指定する場合は、namespace
メソッドを使用します。Another common use-case for route
groups is assigning the same PHP namespace to a
group of controllers using the
namespace
method:
Route::namespace('Admin')->group(function () {
// "App\Http\Controllers\Admin"名前空間下のコントローラ
});
App\Http\Controllers
名前空間をコントローラールート登録時に毎回指定しなくても済むように、デフォルトでRouteServiceProvider
が名前空間グループの中でroutes.php
ファイルを読み込み、指定していることを覚えておいてください。これにより、先頭のApp\Http\Controllers
名前空間を省略でき、続きの部分を指定するだけで済みます。Remember, by default, the
RouteServiceProvider
includes your
route files within a namespace group, allowing you
to register controller routes without specifying the
full App\Http\Controllers
namespace
prefix. So, you 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
handle sub-domain routing. 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 by calling the the
domain
method before defining the
group:
Route::domain('{account}.myapp.com')->group(function () {
Route::get('user/{id}', function ($account, $id) {
//
});
});
ルートプレフィックスRoute Prefixes
prefix
メソッドはグループ内の各ルートに対して、指定されたURIのプレフィックスを指定するために使用します。たとえばグループ内の全ルートのURIにadmin
を付けたければ、次のように指定します。The prefix
method
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::prefix('admin')->group(function () {
Route::get('users', function () {
// Matches The "/admin/users" URL
});
});
モデル結合ルートRoute Model Binding
ルートかコントローラアクションへモデルIDが指定される場合、IDに対応するそのモデルを取得するため、大抵の場合クエリします。Laravelのモデル結合はルートへ直接、そのモデルインスタンスを自動的に注入する便利な手法を提供しています。つまり、ユーザーのIDが渡される代わりに、指定されたIDに一致するUser
モデルインスタンスが渡されます。When injecting a model ID to a
route or controller action, you will often query to
retrieve the model that corresponds to that ID.
Laravel route model binding provides a convenient
way to automatically inject the model instances
directly 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 automatically resolves Eloquent models defined in routes or controller actions whose type-hinted variable names match a route segment name. For example:
Route::get('api/users/{user}', function (App\User $user) {
return $user->email;
});
$user
変数がApp\User
Eloquentモデルとしてタイプヒントされており、変数名が{user}
URIセグメントと一致しているため、Laravelは、リクエストされたURIの対応する値に一致するIDを持つ、モデルインスタンスを自動的に注入します。一致するモデルインスタンスがデータベースへ存在しない場合、404
HTTPレスポンスが自動的に生成されます。Since the
$user
variable is type-hinted as the
App\User
Eloquent model and the
variable name matches the {user}
URI
segment, Laravel will automatically inject the model
instance that has an ID matching the corresponding
value from the request URI. If a matching model
instance is not found in the database, a 404 HTTP
response will automatically be generated.
キー名のカスタマイズCustomizing The Key Name
指定されたモデルクラス取得時に、id
以外のデータベースカラムをモデル結合で使用したい場合、EloquentモデルのgetRouteKeyName
メソッドをオーバーライドしてください。If you would like model binding
to use a database column other than id
when retrieving a given model class, you may
override the getRouteKeyName
method on
the 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 explicit model bindings in the
boot
method of the
RouteServiceProvider
class:
public function boot()
{
parent::boot();
Route::model('user', App\User::class);
}
次に{user}
パラメーターを含むルートを定義します。Next, define a route that
contains a {user}
parameter:
Route::get('profile/{user}', function (App\User $user) {
//
});
{user}
パラメーターをApp\User
モデルへ結合しているため、User
インスタンスはルートへ注入されます。ですからたとえば、profile/1
のリクエストでは、IDが1
のUser
インスタンスが注入されます。Since we have bound all
{user}
parameters 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 from the
database 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 may use the
Route::bind
method. The
Closure
you pass to the
bind
method will receive the value of
the URI segment and should return the instance of
the class that should be injected into the
route:
public function boot()
{
parent::boot();
Route::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
ヘルパ関数を使用することもできます。You may use the
method_field
helper to generate the
_method
input:
{{ method_field('PUT') }}
現在のルートへのアクセスAccessing The Current Route
送信されたリクエストを処理しているルートに関する情報へアクセスするには、Route
ファサードへcurrent
、currentRouteName
、currentRouteAction
メソッドを使用します。You may use the
current
, currentRouteName
,
and currentRouteAction
methods on the
Route
facade to access information
about the route handling the incoming
request:
$route = Route::current();
$name = Route::currentRouteName();
$action = Route::currentRouteAction();
組み込まれている全メソッドを確認するには、Routeファサードの裏で動作しているクラスと、Routeインスタンスの2つについてのAPIドキュメントを参照してください。Refer to the API documentation for both the underlying class of the Route facade[https://laravel.com/api/{{version}}/Illuminate/Routing/Router.html] and Route instance[https://laravel.com/api/{{version}}/Illuminate/Routing/Route.html] to review all accessible methods.