2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Laravel5の複数ルーティングファイル作成時の順番について

2
Last updated at Posted at 2018-12-17

はじめに

Laravel5.3からRouteServiceProvider.phpを拡張すると、複数ファイルでルーティングを管理出来るようになりました。
例えば以下のように分けることができます。

  • 一般用ルーティング(web.php)
  • 管理者用ルーティング(admin.php)

この時よくあるユースケースとして、サブドメイン等を運用しているとURIが重複することがあるので、順番を意識して設定する必要があります。

環境

  • Laravel 5.7
  • PHP 7.2

RouteServiceProvider.php

まずは拡張設定。
map()メソッドで、デフォルトの**mapWebRoutes()より上に**追記してください。

app/Providers/RouteServiceProvider.php
public function map()
{
  $this->mapAdminRoutes(); // 追記
  $this->mapWebRoutes();
}

(中略)

// ここから追記
protected function mapAdminRoutes()
{
  Route::middleware('web')
    ->namespace($this->namespace)
    ->group(base_path('routes/admin.php'));
}
// ここまで

protected function mapWebRoutes()
{
  Route::middleware('web')
    ->namespace($this->namespace)
    ->group(base_path('routes/web.php'));
}

routesディレクトリにadmin.phpを作成する

書き方は通常のルーティングと同じです。
サブドメインを使う場合はdomainメソッドを使います。

routes/admin.php
<?php
Route::domain('admin.hogehoge.com')->group(function () {
  Route::get('/', 'AdminController@index');
});

元のweb.phpに同じURIを設定し、ルーティング先には異なるコントローラーを指定してみます。

routes/web.php
Route::get('/', 'PageController@index');

以上の設定で、

  • http://admin.hogehoge.com の場合はAdminController@index
  • http://hogehoge.com の場合はPageController@index

にルーティングされるようになりました。

ルーティングは先に記述されたほうが優先される

RouteServiceProvider.phpmapWebRoutes()を先に読み込んでしまうと、サブドメインでのアクセス時もPageController@indexにルーティングされてしまいます。
これは単一ファイルで運用した場合でも同様、先に記述したほうが優先されます。

結論

システムが大きくなってくると、Routeファイルが何百行にもなったりgroupメソッドのネストなどが増えやすいので、複数ファイルで管理できるのはスッキリして良いですが、その際は読み込み順番を気にしましょう。

2
4
8

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?