Laravelでルーティングを分けたい

laravelのweb.phpに書いていたルーティングが肥大化していたので、分割してみました。

手順

  1. RouteServiceProvider.phpで追加したいルーティングファイルを追記する。
  2. routeフォルダ直下にファイルを作成し、ルーティングを記述する。
  3. routeキャッシュのクリア

1. RouteServiceProvider.phpで追加したいルーティングファイルを追記する。

今回はホテルの予約システムを想定したいたので、ゲスト(guest.php)と管理画面(hotel.php)を作成します。

※web.phpに集まっているファイルの分割のため、midlewareはwebを引き継ぐことを想定しています。

変更する場所は38行目あたりです。

RouteServiceProvider.php
public function boot()
    {
        $this->configureRateLimiting();

        $this->routes(function () {
            Route::prefix('api')
                ->middleware('api')
                ->namespace($this->namespace)
                ->group(base_path('routes/api.php'));

            Route::middleware('web')
                ->namespace($this->namespace)
                ->group(base_path('routes/web.php'));

            Route::middleware('web')
                ->namespace($this->namespace)
                ->group(base_path('routes/guest.php'));
            
            Route::middleware('web')
                ->namespace($this->namespace)
                ->group(base_path('routes/hotel.php'));
        });
    }

2. routeフォルダ直下にファイルを作成し、ルーティングを記述する。

web.phpと同じように記述しつつ必要なルーティングを記述します。

guest.php
<?php

use Illuminate\Support\Facades\Route;


/*
|--------------------------------------------------------------------------
| Guest Routes
|--------------------------------------------------------------------------
|
|
*/

Route::get('/guest', [App\Http\Controllers\GuestController::class, 'home'])->name('guest.home');

Route::group(['middleware' => ['auth']], function () {
    Route::get('/guest/home', [App\Http\Controllers\GuestController::class, 'index'])->name('guest.index');
});


3. routeキャッシュのクリア

Laravelはキャッシュが強く、ルーティングが反映されない場合があります。必要に応じてキャッシュを削除しましょう。

php artisan route:clear