基本的なルーティングBasic Routing
もっとも基本的なLaravelルートはURIとクロージャを引数に取り、複雑なルーティング設定ファイルなしでもルートと動作を定義できる、非常にシンプルで表現力豊かなメソッドを提供しています。The most basic Laravel routes accept a URI and a closure, providing a very simple and expressive method of defining routes and behavior without complicated routing configuration files:
use Illuminate\Support\Facades\Route;
Route::get('/greeting', function () {
return 'Hello World';
});
デフォルトルートファイルThe Default Route Files
すべてのLaravelルートは、routes
ディレクトリにあるルートファイルで定義されます。これらのファイルは、アプリケーションのbootstrap/app.php
ファイルで指定されている設定を使い、Laravelが自動的にロードします。routes/web.php
ファイルはウェブインターフェイス用のルートを定義します。これらのルートは、セッション状態やCSRF保護などの機能を提供しているweb
ミドルウェアグループを指定してあります。All Laravel routes are defined in
your route files, which are located in the
routes
directory. These files are
automatically loaded by Laravel using the
configuration specified in your application's
bootstrap/app.php
file. The
routes/web.php
file defines routes that
are for your web interface. These routes are
assigned the web
middleware
group[/docs/{{version}}/middleware#laravels-default-middleware-groups],
which provides features like session state and CSRF
protection.
ほとんどのアプリケーションでは、routes/web.php
ファイルでルートを定義することから始めます。routes/web.php
で定義したルートは、ブラウザでその定義したルートのURLを入力することでアクセスできます。たとえば、ブラウザでhttp://example.com/user
に移動すると、次のルートにアクセスできます。For most applications, you will
begin by defining routes in your
routes/web.php
file. The routes defined
in routes/web.php
may be accessed by
entering the defined route's URL in your browser.
For example, you may access the following route by
navigating to http://example.com/user
in your browser:
use App\Http\Controllers\UserController;
Route::get('/user', [UserController::class, 'index']);
APIルートAPI Routes
あなたのアプリケーションが、ステートレスAPIも提供する場合、install:api
Artisanコマンドを使用してAPIルーティングを有効にしてください。If your application will also
offer a stateless API, you may enable API routing
using the install:api
Artisan
command:
php artisan install:api
install:api
コマンドは、Laravel
Sanctumをインストールします。これは、サードパーティのAPIコンシューマ、SPA、またはモバイルアプリケーションの認証に使用できる、堅牢でありながらシンプルなAPIトークン認証ガードを提供します。さらに、install:api
コマンドはroutes/api.php
ファイルを作成します。The install:api
command installs Laravel
Sanctum[/docs/{{version}}/sanctum], which
provides a robust, yet simple API token
authentication guard which can be used to
authenticate third-party API consumers, SPAs, or
mobile applications. In addition, the
install:api
command creates the
routes/api.php
file:
Route::get('/user', function (Request $request) {
return $request->user();
})->middleware('auth:sanctum');
routes/api.php
のルートはステートレスで、api
ミドルウェアグループが指定されます。さらに、/api
URIプレフィックスがこれらのルートに自動的に適用されるため、ファイル内のすべてのルートへ手作業で適用する必要はありません。アプリケーションのbootstrap/app.php
ファイルを修正して、このプレフィックスを変更できます。The routes in
routes/api.php
are stateless and are
assigned to the api
middleware
group[/docs/{{version}}/middleware#laravels-default-middleware-groups].
Additionally, the /api
URI prefix is
automatically applied to these routes, so you do not
need to manually apply it to every route in the
file. You may change the prefix by modifying your
application's bootstrap/app.php
file:
->withRouting(
api: __DIR__.'/../routes/api.php',
apiPrefix: 'api/admin',
// ...
)
利用可能なルーターメソッド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
メソッドを使用して行います。または、any
メソッドを使用して、すべてのHTTP動詞に応答するルートを登録することもできます。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('/', function () {
// ...
});
Note: 同じURIの複数のルートを定義する場合、
get
、post
、put
、patch
、delete
、options
の各メソッドを使ったルートは、any
、match
、redirect
の各メソッドを使ったルートよりも先に定義する必要があります。これにより、受信リクエストが正しいルートにマッチします。[!NOTE]
When defining multiple routes that share the same URI, routes using theget
,post
,put
,patch
,delete
, andoptions
methods should be defined before routes using theany
,match
, andredirect
methods. This ensures the incoming request is matched with the correct route.
依存注入Dependency Injection
ルートのコールバックの引数にタイプヒントにより、そのルートで必要な依存関係を指定できます。宣言した依存関係は、Laravelサービスコンテナにより、自動的に解決されコールバックへ注入されます。たとえば、Illuminate\Http\Request
クラスのタイプヒントを指定して、現在のHTTPリクエストをルートコールバックへ自動的に注入できます。You may type-hint any
dependencies required by your route in your route's
callback signature. The declared dependencies will
automatically be resolved and injected into the
callback by the Laravel service
container[/docs/{{version}}/container]. For
example, you may type-hint the
Illuminate\Http\Request
class to have
the current HTTP request automatically injected into
your route callback:
use Illuminate\Http\Request;
Route::get('/users', function (Request $request) {
// ...
});
CSRF保護CSRF Protection
web
ルートファイルで定義したPOST
、PUT
、PATCH
、DELETE
ルートへ送るHTMLフォームには、CSRFトークンフィールドを含める必要があることに注意してください。含めていない場合、リクエストは拒否されます。CSRF保護の詳細については、CSRFドキュメントをご覧ください。Remember, any HTML forms pointing
to POST
, PUT
,
PATCH
, 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
...
</form>
ルートのリダイレクトRedirect Routes
別のURIにリダイレクトするルートを定義する場合は、Route::redirect
メソッドを使用します。このメソッドは便利なショートカットを提供しているため、単純なリダイレクトを実行するために完全なルートまたはコントローラを定義する必要はありません。If you are defining a route that
redirects to another URI, you may use the
Route::redirect
method. This method
provides a convenient shortcut so that you do not
have to define a full route or controller for
performing a simple redirect:
Route::redirect('/here', '/there');
デフォルトでRoute::redirect
は302
ステータスコードを返します。オプションの3番目のパラメータによりステータスコードをカスタマイズできます。By default,
Route::redirect
returns a
302
status code. You may customize the
status code using the optional third
parameter:
Route::redirect('/here', '/there', 301);
もしくは、Route::permanentRedirect
メソッドを使用して301
ステータスコードを返すことも可能です。Or, you may use the
Route::permanentRedirect
method to
return a 301
status code:
Route::permanentRedirect('/here', '/there');
Warning! リダイレクトルートでルートパラメータを使用する場合、以降のパラメータはLaravelによって予約されており、使用できません。:
destination
、status
[!WARNING]
When using route parameters in redirect routes, the following parameters are reserved by Laravel and cannot be used:destination
andstatus
.
ビュールートView Routes
ルートがビューのみを返す場合は、Route::view
メソッドを使用します。redirect
メソッドと同様に、このメソッドは単純なショートカットを提供しているため、完全なルートやコントローラを定義する必要はありません。view
メソッドは最初の引数にURI、2番目にビュー名を取ります。さらに、オプションとして3番目の引数にビューへ渡すデータの配列を指定できます。If your route only needs to
return a view[/docs/{{version}}/views], you
may use the Route::view
method. Like
the redirect
method, this method
provides a simple shortcut so that you do not have
to define a full route or controller. The
view
method accepts a URI as its first
argument and a view name as its second argument. In
addition, you may provide an array of data to pass
to the view as an optional third
argument:
Route::view('/welcome', 'welcome');
Route::view('/welcome', 'welcome', ['name' => 'Taylor']);
Warning! ビュールートでルートパラメータを使用する場合、次のパラメータはLaravelによって予約されており、使用できません。:
view
、data
、status
、headers
[!WARNING]
When using route parameters in view routes, the following parameters are reserved by Laravel and cannot be used:view
,data
,status
, andheaders
.
ルート一覧Listing Your Routes
route:list
Artisanコマンドは、アプリケーションで定義しているすべてのルートの概要を簡単に提供してくれます。The route:list
Artisan command can easily provide an overview of
all of the routes that are defined by your
application:
php artisan route:list
デフォルトでは、各ルートへ割り付けたルートミドルウェアは、route:list
出力に表示されませんが、コマンドに-v
オプションを追加すると、ルートのミドルウェアとミドルウェアグループを表示できます。By default, the route middleware
that are assigned to each route will not be
displayed in the route:list
output;
however, you can instruct Laravel to display the
route middleware and middleware group names by
adding the -v
option to the
command:
php artisan route:list -v
# ミドルウェアグループも表示
php artisan route:list -vv
また、指定したURIで始まるルートのみを表示するように、Laravelへ指示することもできます。You may also instruct Laravel to only show routes that begin with a given URI:
php artisan route:list --path=api
さらに、route:list
コマンドを実行するときに、--except-vendor
オプションを指定すると、サードパーティーのパッケージが定義したルートを非表示にできます。In addition, you may instruct
Laravel to hide any routes that are defined by
third-party packages by providing the
--except-vendor
option when executing
the route:list
command:
php artisan route:list --except-vendor
同様に、route:list
コマンドを実行するときに、--only-vendor
オプションを指定し、サードパーティーのパッケージが定義したルートだけを表示できます。Likewise, you may also instruct
Laravel to only show routes that are defined by
third-party packages by providing the
--only-vendor
option when executing the
route:list
command:
php artisan route:list --only-vendor
ルートのカスタマイズRouting Customization
デフォルトで、アプリケーションのルートはbootstrap/app.php
ファイルで設定、ロードします。By default, your application's
routes are configured and loaded by the
bootstrap/app.php
file:
<?php
use Illuminate\Foundation\Application;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)->create();
しかし、アプリケーションのルートのサブセットを含む、全く新しいファイルを定義したいこともあるでしょう。これをおこなうには、withRouting
メソッドでthen
クロージャを指定してください。このクロージャの中で、アプリケーションで必要な追加のルートを登録できます。However, sometimes you may want
to define an entirely new file to contain a subset
of your application's routes. To accomplish this,
you may provide a then
closure to the
withRouting
method. Within this
closure, you may register any additional routes that
are necessary for your application:
use Illuminate\Support\Facades\Route;
->withRouting(
web: __DIR__.'/../routes/web.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
then: function () {
Route::middleware('api')
->prefix('webhooks')
->name('webhooks.')
->group(base_path('routes/webhooks.php'));
},
)
あるいは、withRouting
メソッドへusing
クロージャを指定し、ルート登録を完全に制御することもできます。この引数を渡すと、フレームワークではHTTPルートを登録しないため、すべてのルートを手作業で登録してください。Or, you may even take complete
control over route registration by providing a
using
closure to the
withRouting
method. When this argument
is passed, no HTTP routes will be registered by the
framework and you are responsible for manually
registering all routes:
use Illuminate\Support\Facades\Route;
->withRouting(
commands: __DIR__.'/../routes/console.php',
using: function () {
Route::middleware('api')
->prefix('api')
->group(base_path('routes/api.php'));
Route::middleware('web')
->group(base_path('routes/web.php'));
},
)
ルートパラメータRoute Parameters
必須パラメータRequired Parameters
ルート内のURIのセグメントを取得したい場合があるでしょう。たとえば、URLからユーザーのIDを取得する必要のある場合があります。これを行うにはルートパラメータを定義します。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 (string $id) {
return 'User '.$id;
});
ルートに必要なだけの数のルートパラメータを定義できます。You may define as many route parameters as required by your route:
Route::get('/posts/{post}/comments/{comment}', function (string $postId, string $commentId) {
// ...
});
ルートパラメータは常に{}
中括弧で囲こみ、アルファベットで構成する必要があります。ルートパラメータ名にはアンダースコア(_
)も使用できます。ルートパラメータは順序に基づいて、ルートのコールバック/コントローラに注入されます。ルートのコールバック/コントローラの引数名は考慮されません。Route parameters are always
encased within {}
braces and should
consist of alphabetic characters. Underscores
(_
) are also acceptable within route
parameter names. Route parameters are injected into
route callbacks / controllers based on their order -
the names of the route callback / controller
arguments do not matter.
パラメータと依存注入Parameters and Dependency Injection
Laravelサービスコンテナにより、ルートのコールバックへ自動的に注入してもらいたい依存がある場合は、依存のタイプヒントの後にルートパラメータをリストする必要があります。If your route has dependencies that you would like the Laravel service container to automatically inject into your route's callback, you should list your route parameters after your dependencies:
use Illuminate\Http\Request;
Route::get('/user/{id}', function (Request $request, string $id) {
return 'User '.$id;
});
オプションパラメータOptional Parameters
場合により、いつもURIに存在するとは限らないルートパラメータを指定する必要が起きます。パラメータ名の後に?
マークを付けるとオプション指定になります。ルートの対応する変数にデフォルト値も指定してください。Occasionally you may need to
specify a route parameter that may not always be
present in the URI. 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 (?string $name = null) {
return $name;
});
Route::get('/user/{name?}', function (?string $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 (string $name) {
// ...
})->where('name', '[A-Za-z] ');
Route::get('/user/{id}', function (string $id) {
// ...
})->where('id', '[0-9] ');
Route::get('/user/{id}/{name}', function (string $id, string $name) {
// ...
})->where(['id' => '[0-9] ', 'name' => '[a-z] ']);
使いやすいように、一般的に使用される正規表現パターンには、ルートにパターン制約をすばやく追加できるようにヘルパメソッドを用意しています。For convenience, some commonly used regular expression patterns have helper methods that allow you to quickly add pattern constraints to your routes:
Route::get('/user/{id}/{name}', function (string $id, string $name) {
// ...
})->whereNumber('id')->whereAlpha('name');
Route::get('/user/{name}', function (string $name) {
// ...
})->whereAlphaNumeric('name');
Route::get('/user/{id}', function (string $id) {
// ...
})->whereUuid('id');
Route::get('/user/{id}', function (string $id) {
//
})->whereUlid('id');
Route::get('/category/{category}', function (string $category) {
// ...
})->whereIn('category', ['movie', 'song', 'painting']);
受信リクエストがルートパターンの制約と一致しない場合、404 HTTPレスポンスを返します。If the incoming request does not match the route pattern constraints, a 404 HTTP response will be returned.
グローバル制約Global Constraints
ルートパラメータを指定した正規表現で常に制約したい場合は、pattern
メソッドを使用します。これらのパターンは、アプリケーションのApp\Providers\AppServiceProvider
クラスの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
application's
App\Providers\AppServiceProvider
class:
use Illuminate\Support\Facades\Route;
/**
* アプリケーションの全サービスの初期起動処理
*/
public function boot(): void
{
Route::pattern('id', '[0-9] ');
}
パターンを定義すれば、パラメータ名によりすべてのルートで自動的に適用されます。Once the pattern has been defined, it is automatically applied to all routes using that parameter name:
Route::get('/user/{id}', function (string $id) {
// {id}が数値の場合にのみ実行される
});
エンコードされたスラッシュEncoded Forward Slashes
Laravelルーティングコンポーネントでは、/
を除くすべての文字をルートパラメータ値内に含めることができます。/
がプレースホルダーの一部になることを明示的に許可する場合は、where
条件の正規表現を使用する必要があります。The Laravel routing component
allows all characters except /
to be
present within route parameter values. You must
explicitly allow /
to be part of your
placeholder using a where
condition
regular expression:
Route::get('/search/{search}', function (string $search) {
return $search;
})->where('search', '.*');
[!WARNING]
Warning! エンコードされたスラッシュは、最後のルートセグメント内でのみサポートされます。
Encoded forward slashes are only supported within the last route segment.
名前付きルート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',
[UserProfileController::class, 'show']
)->name('profile');
[!WARNING]
Warning! ルート名は常に一意である必要があります。
Route names should always be unique.
名前付きルートのURL生成Generating URLs to Named Routes
特定のルートに名前を割り当てたら、Laravelのroute
およびredirect
ヘルパ関数を使い、URLやリダイレクトを生成するときにルートの名前を使用できます。Once you have assigned a name to
a given route, you may use the route's name when
generating URLs or redirects via Laravel's
route
and redirect
helper
functions:
// URLを生成
$url = route('profile');
// リダイレクトの生成
return redirect()->route('profile');
return to_route('profile');
名前付きルートがパラメータを定義している場合は、パラメータを2番目の引数としてroute
関数に渡してください。指定したパラメータは、生成する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 generated URL in their correct
positions:
Route::get('/user/{id}/profile', function (string $id) {
// ...
})->name('profile');
$url = route('profile', ['id' => 1]);
配列に追加のパラメーターを渡すと、それらのキー/値ペアが生成するURLのクエリ文字列へ自動的に追加されます。If you pass additional parameters in the array, those key / value pairs will automatically be added to the generated URL's query string:
Route::get('/user/{id}/profile', function (string $id) {
// ...
})->name('profile');
$url = route('profile', ['id' => 1, 'photos' => 'yes']);
// /user/1/profile?photos=yes
Note: 場合により現在のロケールなど、URLパラメータにリクエスト全体のデフォルト値を指定したいことがあります。これを実現するには、
URL::defaults
メソッドを使用してください。[!NOTE]
Sometimes, you may wish to specify request-wide default values for URL parameters, such as the current locale. To accomplish this, you may use theURL::defaults
method[/docs/{{version}}/urls#default-values].
現在のルートの検査Inspecting the Current Route
現在のリクエストが特定の名前付きルートにルーティングされたかどうかを確認したい場合は、Routeインスタンスでnamed
メソッドを使用できます。たとえば、ルートミドルウェアから現在のルート名を確認できます。If you would like to determine if
the current request was routed to a given named
route, you may use the named
method on
a Route instance. For example, you may check the
current route name from a route
middleware:
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* 受信リクエストの処理
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
if ($request->route()->named('profile')) {
// ...
}
return $next($request);
}
ルートグループRoute Groups
ルートグループを使用すると、ミドルウェアなどのルート属性を個々のルートごとに定義することなく、多数のルート間で共有できます。Route groups allow you to share route attributes, such as middleware, across a large number of routes without needing to define those attributes on each individual route.
ネストされたグループは、属性を親グループとインテリジェントに「マージ」しようとします。ミドルウェアとwhere
条件は、指定する名前やプレフィックスと同時にマージされます。URIプレフィックスの名前空間区切り文字とスラッシュは、必要に応じて自動的に追加されます。Nested groups attempt to
intelligently "merge" attributes with
their parent group. Middleware and
where
conditions are merged while names
and prefixes are appended. Namespace delimiters and
slashes in URI prefixes are automatically added
where appropriate.
ミドルウェアMiddleware
ミドルウェアをグループ内すべてのルートに割り当てるには、グループを定義する前にmiddleware
メソッドを使用します。ミドルウェアは、配列にリストする順序で実行します。To assign
middleware[/docs/{{version}}/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 () {
// 1番目と2番目のミドルウェアを使用
});
Route::get('/user/profile', function () {
// 1番目と2番目のミドルウェアを使用
});
});
コントローラControllers
ルートのグループがすべて同じコントローラを利用する場合、controller
メソッドを使用して、グループ内のすべてのルートに共通のコントローラを定義できます。これにより、ルートを定義時に、そのルートが呼び出すコントローラメソッドを指定するだけでよくなります。If a group of routes all utilize
the same
controller[/docs/{{version}}/controllers],
you may use the controller
method to
define the common controller for all of the routes
within the group. Then, when defining the routes,
you only need to provide the controller method that
they invoke:
use App\Http\Controllers\OrderController;
Route::controller(OrderController::class)->group(function () {
Route::get('/orders/{id}', 'show');
Route::post('/orders', 'store');
});
サブドメインルーティングSubdomain Routing
ルートグループは、サブドメインルーティングを処理するためにも使用できます。サブドメインには、ルートURIと同じようにルートパラメータを割り当てることができ、ルートまたはコントローラで使用するためにサブドメインの一部を取得できます。サブドメインは、グループを定義する前にdomain
メソッドを呼び出し指定します。Route groups may also be used to
handle subdomain routing. Subdomains may be assigned
route parameters just like route URIs, allowing you
to capture a portion of the subdomain for usage in
your route or controller. The subdomain may be
specified by calling the domain
method
before defining the group:
Route::domain('{account}.example.com')->group(function () {
Route::get('user/{id}', function (string $account, string $id) {
// ...
});
});
[!WARNING]
Warning! ルーティングがサブドメインルートに到達できるようにするには、サブドメインなしのドメインルートを登録する前にサブドメインルートを登録しておく必要があります。これにより、サブドメインなしのドメインルートが同じURIパスを持つサブドメインルートを上書きするのを防げます。
In order to ensure your subdomain routes are reachable, you should register subdomain routes before registering root domain routes. This will prevent root domain routes from overwriting subdomain routes which have the same URI path.
ルートプレフィックス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 () {
// /admin/usersのURLに一致
});
});
ルート名のプレフィックスRoute Name Prefixes
name
メソッドを使用して、グループ内の各ルート名の前に特定の文字列を付け加えられます。例として、グループ内のすべてのルートの名前の前にadmin
を付けてみましょう。指定する文字列は、指定したとおりにルート名のプレフィックスとして付けられるため、必ず末尾の.
文字を指定してください。The name
method may
be used to prefix each route name in the group with
a given string. For example, you may want to prefix
the names of all of the routes in the group with
admin
. The given string is prefixed to
the route name exactly as it is specified, so we
will be sure to provide the trailing .
character in the prefix:
Route::name('admin.')->group(function () {
Route::get('/users', function () {
// ルートに"admin.users"が名付けられる
})->name('users');
});
ルートモデル結合Route Model Binding
ルートまたはコントローラアクションでモデルIDを取得する場合、多くはデータベースにクエリを実行して、そのIDに対応するモデルを取得することになります。Laravelルートモデル結合は、モデルインスタンスをルートに直接自動的に注入する利便性を提供しています。たとえば、ユーザーのIDを挿入する代わりに、指定されたIDに一致するUser
モデルインスタンス全体を注入できます。When injecting a model ID to a
route or controller action, you will often query the
database 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は、タイプヒントの変数名がルートセグメント名と一致する、ルートまたはコントローラアクションで定義したEloquentモデルを自動的に解決します。例をご覧ください。Laravel automatically resolves Eloquent models defined in routes or controller actions whose type-hinted variable names match a route segment name. For example:
use App\Models\User;
Route::get('/users/{user}', function (User $user) {
return $user->email;
});
$user
変数はApp\Models\User
Eloquentモデルとしてタイプヒントされ、変数名は{user}
URIセグメントと一致するため、LaravelはリクエストURIの対応する値と一致するIDを持つモデルインスタンスを自動的に挿入します。一致するモデルインスタンスがデータベースに見つからない場合、404
HTTPレスポンスを自動的に生成します。Since the
$user
variable is type-hinted as the
App\Models\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.
もちろん、コントローラメソッドを使用する場合でも暗黙的な結合は可能です。繰り返しになりますが、{user}
URIセグメントはApp\Models\User
タイプヒントを含むコントローラの$user
変数と一致することに注意してください。Of course, implicit binding is
also possible when using controller methods. Again,
note the {user}
URI segment matches the
$user
variable in the controller which
contains an App\Models\User
type-hint:
use App\Http\Controllers\UserController;
use App\Models\User;
// ルート定義
Route::get('/users/{user}', [UserController::class, 'show']);
// コントローラメソッドの定義
public function show(User $user)
{
return view('user.profile', ['user' => $user]);
}
ソフトデリートモデルバインディングSoft Deleted Models
通常、暗黙のモデル結合は、ソフトデリートされたモデルを取得しません。しかし、ルートの定義でwithTrashed
メソッドをチェーンすることにより、こうしたモデルを取得するように暗黙のバインディングで指示できます。Typically, implicit model binding
will not retrieve models that have been soft
deleted[/docs/{{version}}/eloquent#soft-deleting].
However, you may instruct the implicit binding to
retrieve these models by chaining the
withTrashed
method onto your route's
definition:
use App\Models\User;
Route::get('/users/{user}', function (User $user) {
return $user->email;
})->withTrashed();
キーのカスタマイズCustomizing the Key
id
以外の列を使用してEloquentモデルを解決したい場合もあるでしょう。その場合は、ルートパラメータ定義でカラムを指定します。Sometimes you may wish to resolve
Eloquent models using a column other than
id
. To do so, you may specify the
column in the route parameter definition:
use App\Models\Post;
Route::get('/posts/{post:slug}', function (Post $post) {
return $post;
});
特定のモデルクラスを取得するときのモデル結合で、常にid
以外のデータベースカラムを使用する場合は、EloquentモデルのgetRouteKeyName
メソッドをオーバーライドできます。If you would like model binding
to always use a database column other than
id
when retrieving a given model class,
you may override the getRouteKeyName
method on the Eloquent model:
/**
* モデルのルートキーの取得
*/
public function getRouteKeyName(): string
{
return 'slug';
}
カスタムキーとスコープCustom Keys and Scoping
単一のルート定義で複数のEloquentモデルを暗黙的にバインドする場合、前のEloquentモデルの子である必要があるように、2番目のEloquentモデルのスコープの設定をおすすめします。たとえば、特定のユーザーのブログ投稿をスラッグで取得する次のルート定義について考えてみます。When implicitly binding multiple Eloquent models in a single route definition, you may wish to scope the second Eloquent model such that it must be a child of the previous Eloquent model. For example, consider this route definition that retrieves a blog post by slug for a specific user:
use App\Models\Post;
use App\Models\User;
Route::get('/users/{user}/posts/{post:slug}', function (User $user, Post $post) {
return $post;
});
ネストしたルートパラメーターとしてカスタムキー付き暗黙的結合を使用する場合、Laravelはクエリのスコープを自動的に設定し、親の関係名を推測する規則を使用して、親によってネストされたモデルを取得します。この場合、User
モデルには、Post
モデルを取得するために使用できるposts
(ルートパラメータ名の複数形)という名前のリレーションが存在していると仮定します。When using a custom keyed
implicit binding as a nested route parameter,
Laravel will automatically scope the query to
retrieve the nested model by its parent using
conventions to guess the relationship name on the
parent. In this case, it will be assumed that the
User
model has a relationship named
posts
(the plural form of the route
parameter name) which can be used to retrieve the
Post
model.
必要であれば、カスタムキーを指定しない場合でも、Laravelへ「子」のバインドをスコープするように指示できます。それにはルート定義時に、scopeBindings
メソッドを呼び出してください。If you wish, you may instruct
Laravel to scope "child" bindings even
when a custom key is not provided. To do so, you may
invoke the scopeBindings
method when
defining your route:
use App\Models\Post;
use App\Models\User;
Route::get('/users/{user}/posts/{post}', function (User $user, Post $post) {
return $post;
})->scopeBindings();
もしくは、グループのルート定義全体へスコープ付きバインドを使用するよう指示することもできます。Or, you may instruct an entire group of route definitions to use scoped bindings:
Route::scopeBindings()->group(function () {
Route::get('/users/{user}/posts/{post}', function (User $user, Post $post) {
return $post;
});
});
同様に、withoutScopedBindings
メソッドを呼び出すことで、バインドをスコープしないよう明示的にLaravelへ指示できます。Similarly, you may explicitly
instruct Laravel to not scope bindings by invoking
the withoutScopedBindings
method:
Route::get('/users/{user}/posts/{post:slug}', function (User $user, Post $post) {
return $post;
})->withoutScopedBindings();
見つからないモデルの動作をカスタマイズするCustomizing Missing Model Behavior
暗黙的にバインドされたモデルが見つからない場合、通常404のHTTPレスポンスが生成されます。ただし、ルートを定義するときにMissing
メソッドを呼び出し、この動作をカスタマイズできます。Missing
メソッドは、暗黙的にバインドされたモデルが見つからない場合に呼び出されるクロージャを引数に取ります。Typically, a 404 HTTP response
will be generated if an implicitly bound model is
not found. However, you may customize this behavior
by calling the missing
method when
defining your route. The missing
method
accepts a closure that will be invoked if an
implicitly bound model can not be found:
use App\Http\Controllers\LocationsController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
Route::get('/locations/{location:slug}', [LocationsController::class, 'show'])
->name('locations.view')
->missing(function (Request $request) {
return Redirect::route('locations.index');
});
暗黙のEnumバインディングImplicit Enum Binding
PHP8.1から、Enumsのサポートが導入されました。この機能を補完するために、Laravelではルート定義に「値に依存した(backed)」Enumsをタイプヒントすることができ、Laravelはそのルートセグメントが有効なEnum値に対応する場合のみルートを呼び出します。そうでない場合は、404 HTTPレスポンスが自動的に返されます。例えば、次のようなEnumがあるとします。PHP 8.1 introduced support for Enums[https://www.php.net/manual/en/language.enumerations.backed.php]. To complement this feature, Laravel allows you to type-hint a string-backed Enum[https://www.php.net/manual/en/language.enumerations.backed.php] on your route definition and Laravel will only invoke the route if that route segment corresponds to a valid Enum value. Otherwise, a 404 HTTP response will be returned automatically. For example, given the following Enum:
<?php
namespace App\Enums;
enum Category: string
{
case Fruits = 'fruits';
case People = 'people';
}
{category}
ルートセグメントが、fruits
またはpeople
である場合にのみ呼び出されるルートを定義できます。そうでなければ、Laravelは404
HTTPレスポンスを返します。You may define a
route that will only be invoked if the
{category}
route segment is
fruits
or people
.
Otherwise, Laravel will return a 404 HTTP
response:
use App\Enums\Category;
use Illuminate\Support\Facades\Route;
Route::get('/categories/{category}', function (Category $category) {
return $category->value;
});
明示的な結合Explicit Binding
モデル結合を使用するために、Laravelの暗黙的な規約ベースのモデル解決を使用する必要はありません。ルートパラメータとモデルの対応を明示的に定義することもできます。明示的な結合を登録するときは、ルーターのmodel
メソッドを使用して、パラメータのクラスを指定します。明示的なモデルバインディングはAppServiceProvider
クラスのboot
メソッドの最初で定義してください。You are not required to use
Laravel's implicit, convention based model
resolution in order to use model binding. You can
also explicitly define how route parameters
correspond to models. 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 at the
beginning of the boot
method of your
AppServiceProvider
class:
use App\Models\User;
use Illuminate\Support\Facades\Route;
/**
* アプリケーションの全サービスの初期起動処理
*/
public function boot(): void
{
Route::model('user', User::class);
}
次に、{user}
パラメータを含むルートを定義します。Next, define a route that
contains a {user}
parameter:
use App\Models\User;
Route::get('/users/{user}', function (User $user) {
// ...
});
すべての{user}
パラメータをApp\Models\User
モデルに結合したので、このクラスのインスタンスがルートに注入されます。したがって、たとえばusers/1
へのリクエストは、IDが1
のデータベースからUser
インスタンスを注入します。Since we have bound all
{user}
parameters to the
App\Models\User
model, an instance of
that class will be injected into the route. So, for
example, a request to users/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セグメントの値を受け取り、ルートへ注入するクラスのインスタンスを返します。繰り返しますが、このカスタマイズはアプリケーションの
AppServiceProvider
のboot
メソッドで行う必要があります。If you wish to define your own
model binding 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. Again, this customization should take
place in the boot
method of your
application's
AppServiceProvider
:
use App\Models\User;
use Illuminate\Support\Facades\Route;
/**
* アプリケーションの全サービスの初期起動処理
*/
public function boot(): void
{
Route::bind('user', function (string $value) {
return User::where('name', $value)->firstOrFail();
});
}
別の方法として、EloquentモデルのresolveRouteBinding
メソッドをオーバーライドすることもできます。このメソッドはURIセグメントの値を受け取り、ルートに挿入する必要があるクラスのインスタンスを返す必要があります。Alternatively, you may override
the resolveRouteBinding
method on your
Eloquent model. This method will receive the value
of the URI segment and should return the instance of
the class that should be injected into the
route:
/**
* 値と結合するモデルの取得
*
* @param mixed $value
* @param string|null $field
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function resolveRouteBinding($value, $field = null)
{
return $this->where('name', $value)->firstOrFail();
}
ルートが明確な結合のスコープを利用している場合、resolveChildRouteBinding
メソッドを使用して親モデルの子結合を解決します。If a route is utilizing
implicit binding
scoping[#implicit-model-binding-scoping],
the resolveChildRouteBinding
method
will be used to resolve the child binding of the
parent model:
/**
* 値と結合するモデルの取得
*
* @param string $childType
* @param mixed $value
* @param string|null $field
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function resolveChildRouteBinding($childType, $value, $field)
{
return parent::resolveChildRouteBinding($childType, $value, $field);
}
フォールバックルートFallback Routes
Route::fallback
メソッドを使用して、全ルートが受信リクエストと一致しない場合に実行するルートを定義できます。通常、未処理のリクエストは、アプリケーションの例外ハンドラを介して「404」ページを自動的にレンダします。しかし、通常はroutes/web.php
ファイル内でfallback
ルートを定義しますので、web
ミドルウェアグループ内のすべてのミドルウェアがルートに適用されるわけです。必要に応じ、このルートにミドルウェアを自由に追加できます。Using the
Route::fallback
method, you may define
a route that will be executed when no other route
matches the incoming request. Typically, unhandled
requests will automatically render a "404"
page via your application's exception handler.
However, since you would typically define the
fallback
route within your
routes/web.php
file, all middleware in
the web
middleware group will apply to
the route. You are free to add additional middleware
to this route as needed:
Route::fallback(function () {
// ...
});
[!WARNING]
Warning! フォールバックルートは、常にアプリケーションのルート登録で最後に指定してください。
The fallback route should always be the last route registered by your application.
レート制限Rate Limiting
レート制限の定義Defining Rate Limiters
Laravelには、強力でカスタマイズ可能なレート制限サービスがあり、特定のルートやルートグループのトラフィック量を制限するために利用できます。使い始めるには、アプリケーションのニーズに合わせ、レート制限の設定を定義する必要があります。Laravel includes powerful and customizable rate limiting services that you may utilize to restrict the amount of traffic for a given route or group of routes. To get started, you should define rate limiter configurations that meet your application's needs.
Rate limiters may be defined within the boot
method of your application's
App\Providers\AppServiceProvider
class:Rate limiters may be
defined within the boot
method of your
application's
App\Providers\AppServiceProvider
class:
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
/**
* アプリケーションの全サービスの初期起動処理
*/
protected function boot(): void
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});
}
レート制限は、RateLimiter
ファサードのfor
メソッドを使用して定義します。for
メソッドは、レート制限名と、レート制限をしていするルートへ適用する必要がある制限構成を返すクロージャを引数に取ります。制限設定は、Illuminate\Cache\RateLimiting\Limit
クラスのインスタンスです。このクラスには、制限を簡単に定義するのに役立つ「組み立て」メソッドを用意しています。レート制限名は、任意の文字列にできます。Rate limiters are defined using
the RateLimiter
facade's
for
method. The for
method
accepts a rate limiter name and a closure that
returns the limit configuration that should apply to
routes that are assigned to the rate limiter. Limit
configuration are instances of the
Illuminate\Cache\RateLimiting\Limit
class. This class contains helpful
"builder" methods so that you can quickly
define your limit. The rate limiter name may be any
string you wish:
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
/**
* アプリケーションの全サービスの初期起動処理
*/
protected function boot(): void
{
RateLimiter::for('global', function (Request $request) {
return Limit::perMinute(1000);
});
}
受信リクエストが指定したレート制限を超えると、429
HTTPステータスコードのレスポンスをLaravelは自動的に返します。レート制限によって返す独自のレスポンスを定義する場合は、response
メソッドを使用できます。If the incoming request exceeds
the specified rate limit, a response with a 429 HTTP
status code will automatically be returned by
Laravel. If you would like to define your own
response that should be returned by a rate limit,
you may use the response
method:
RateLimiter::for('global', function (Request $request) {
return Limit::perMinute(1000)->response(function (Request $request, array $headers) {
return response('Custom response...', 429, $headers);
});
});
レート制限コールバックは受信HTTPリクエストインスタンスを受け取るため、受信リクエストや認証済みユーザーに基づいて適切なレート制限を動的に構築できます。Since rate limiter callbacks receive the incoming HTTP request instance, you may build the appropriate rate limit dynamically based on the incoming request or authenticated user:
RateLimiter::for('uploads', function (Request $request) {
return $request->user()->vipCustomer()
? Limit::none()
: Limit::perMinute(100);
});
レート制限のセグメント化Segmenting Rate Limits
レート制限を任意の値でセグメント化したい場合があります。たとえばIPアドレスごとに、ユーザーに対し1分間に100回まで特定のルートへアクセス可能にしたい場合です。これを実現するには、レート制限を作成するときにby
メソッドを使用できます。Sometimes you may wish to segment
rate limits by some arbitrary value. For example,
you may wish to allow users to access a given route
100 times per minute per IP address. To accomplish
this, you may use the by
method when
building your rate limit:
RateLimiter::for('uploads', function (Request $request) {
return $request->user()->vipCustomer()
? Limit::none()
: Limit::perMinute(100)->by($request->ip());
});
別の例を使ってこの機能を説明すると、認証されたユーザーIDごとに1分間に100回、ゲスト用のIPアドレスごとに1分間に10回、ルートへのアクセス制限ができます。To illustrate this feature using another example, we can limit access to the route to 100 times per minute per authenticated user ID or 10 times per minute per IP address for guests:
RateLimiter::for('uploads', function (Request $request) {
return $request->user()
? Limit::perMinute(100)->by($request->user()->id)
: Limit::perMinute(10)->by($request->ip());
});
複数のレート制限Multiple Rate Limits
必要に応じて、指定したレート制限設定のレート制限配列を返せます。各レート制限は、配列内へ配置した順序に基づいてルートに対して評価されます。If needed, you may return an array of rate limits for a given rate limiter configuration. Each rate limit will be evaluated for the route based on the order they are placed within the array:
RateLimiter::for('login', function (Request $request) {
return [
Limit::perMinute(500),
Limit::perMinute(3)->by($request->input('email')),
];
});
ルートへのレート制限指定Attaching Rate Limiters to Routes
レート制限は、throttle
ミドルウェアを使用してルートまたはルートグループに指定します。このスロットルミドルウェアは、ルートに割り当てたいレート制限名を引数に取ります。Rate limiters may be attached to
routes or route groups using the
throttle
middleware[/docs/{{version}}/middleware]. The
throttle middleware accepts the name of the rate
limiter you wish to assign to the route:
Route::middleware(['throttle:uploads'])->group(function () {
Route::post('/audio', function () {
// ...
});
Route::post('/video', function () {
// ...
});
});
RedisによるスロットリングThrottling With Redis
throttle
ミドルウェアはデフォルトで、Illuminate\Routing\Middleware\ThrottleRequests
クラスへマッピングします。しかし、アプリケーションのキャッシュドライバとしてRedisを使う場合は、レート制限を管理するためにRedisを使うようにLaravelへ指示したいかもしれません。それには、アプリケーションのbootstrap/app.php
ファイルでthrottleWithRedis
メソッドを使用します。このメソッドはthrottle
ミドルウェアをIlluminate\Routing\Middleware\ThrottleRequestsWithRedis
ミドルウェアクラスへマッピングしますBy default, the
throttle
middleware is mapped to the
Illuminate\Routing\Middleware\ThrottleRequests
class. However, if you are using Redis as your
application's cache driver, you may wish to instruct
Laravel to use Redis to manage rate limiting. To do
so, you should use the
throttleWithRedis
method in your
application's bootstrap/app.php
file.
This method maps the throttle
middleware to the
Illuminate\Routing\Middleware\ThrottleRequestsWithRedis
middleware class:
->withMiddleware(function (Middleware $middleware) {
$middleware->throttleWithRedis();
// ...
})
疑似フォームメソッドForm Method Spoofing
HTMLフォームは、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="/example" method="POST">
<input type="hidden" name="_method" value="PUT">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>
使いやすいように、@method
Bladeディレクティブを使用しても、_method
入力フィールドを生成できます。For convenience, you may use the
@method
Blade
directive[/docs/{{version}}/blade] to
generate the _method
input
field:
<form action="/example" method="POST">
@method('PUT')
@csrf
</form>
現在のルートへのアクセス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:
use Illuminate\Support\Facades\Route;
$route = Route::current(); // Illuminate\Routing\Route
$name = Route::currentRouteName(); // 文字列
$action = Route::currentRouteAction(); // 文字列
ルートとルートクラスで使用可能な全メソッドを確認するには、ルートファサードの元となるクラスとルートインスタンスの両方のAPIドキュメントを参照してくださいYou may 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 of the methods that are available on the router and route classes.
オリジン間リソース共有 (CORS)Cross-Origin Resource Sharing (CORS)
LaravelはCORS OPTIONS
HTTPリクエストに対して、設定した値で自動的にレスポンスできます。OPTIONS
リクエストは、アプリケーションのグローバルミドルウェアスタックに含めているHandleCors
ミドルウェア が自動的に処理します。Laravel can automatically respond
to CORS OPTIONS
HTTP requests with
values that you configure. The OPTIONS
requests will automatically be handled by the
HandleCors
middleware[/docs/{{version}}/middleware] that
is automatically included in your application's
global middleware stack.
アプリケーションのCORS設定値をカスタマイズする必要も起きるでしょう。この場合、config:publish
Artisanコマンドを使用し、cors
設定ファイルをリソース公開します。Sometimes, you may need to
customize the CORS configuration values for your
application. You may do so by publishing the
cors
configuration file using the
config:publish
Artisan
command:
php artisan config:publish cors
This command will place a cors.php
configuration file within your application's
config
directory.This command will place a
cors.php
configuration file within your
application's config
directory.
CORSに関するMDN Webドキュメントを参照してください。[!NOTE]
Note: CORSおよびCORSヘッダの詳細は、
For more information on CORS and CORS headers, please consult the MDN web documentation on CORS[https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#The_HTTP_response_headers].
ルートのキャッシュRoute Caching
アプリケーションを本番環境へデプロイするときは、Laravelのルートキャッシュの利点を利用するべきでしょう。ルートキャッシュを使用すると、アプリケーションのルートをすべて登録ためにかかる時間が大幅に短縮できます。ルートキャッシュを生成するには、route:cache
Artisanコマンドを実行します。When
deploying your application to production, you should
take advantage of Laravel's route cache. Using the
route cache will drastically decrease the amount of
time it takes to register all of your application's
routes. To generate a route cache, execute the
route:cache
Artisan command:
php artisan route:cache
このコマンドを実行した後、キャッシュされたルートファイルはすべてのリクエストでロードされます。新しいルートを追加する場合は、新しいルートキャッシュを生成する必要があることに注意してください。このため、プロジェクトのデプロイ中にのみroute:cache
コマンドを実行する必要があります。After running this command, your
cached routes file will be loaded on every request.
Remember, if you add any new routes you will need to
generate a fresh route cache. Because of this, you
should only run the route:cache
command
during your project's deployment.
route:clear
コマンドを使用して、ルートキャッシュをクリアできます。You may use the
route:clear
command to clear the route
cache:
php artisan route:clear