LoginSignup
19
14

More than 3 years have passed since last update.

[Laravel]ルーティングファイルを分割して管理する

Last updated at Posted at 2020-06-16

Laravelでは基本route/web.phpにルーティングを書いていくことになります。
APIルーティングを書く場合はapi.phpに書くこともあるかと思います。

今回は、アレコレと編集をして新しいルーティングファイルを追加したいと思います。

手順1 新しいルーティングファイルを作成

routeディレクトリ内に新しいルーティングファイルを作ります。[


routes/batch.php

作成したファイルに、適当にルーティングを書いておきましょう。

batch.php
<?php

Route::get('/', function() {
    return 'hoge';
});

手順2 サービスプロバイダに登録

app/Providers/RouteServiceProvider.phpに作成したファイルを登録します。

Before↓

RouteServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\Facades\Route;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * This namespace is applied to your controller routes.
     *
     * In addition, it is set as the URL generator's root namespace.
     *
     * @var string
     */
    protected $namespace = 'App\Http\Controllers';

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        //

        parent::boot();
    }

    /**
     * Define the routes for the application.
     *
     * @return void
     */
    public function map()
    {
        $this->mapApiRoutes();

        $this->mapWebRoutes();

        //
    }

    /**
     * Define the "web" routes for the application.
     *
     * These routes all receive session state, CSRF protection, etc.
     *
     * @return void
     */
    protected function mapWebRoutes()
    {
        Route::middleware('web')
             ->namespace($this->namespace)
             ->group(base_path('routes/web.php'));
    }

    /**
     * Define the "api" routes for the application.
     *
     * These routes are typically stateless.
     *
     * @return void
     */
    protected function mapApiRoutes()
    {
        Route::prefix('api')
             ->middleware('api')
             ->namespace($this->namespace)
             ->group(base_path('routes/api.php'));
    }
}

After↓

RouteServiceProvider.php
<?php

namespace App\Providers;

use Illuminate\Support\Facades\Route;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * This namespace is applied to your controller routes.
     *
     * In addition, it is set as the URL generator's root namespace.
     *
     * @var string
     */
    protected $namespace = 'App\Http\Controllers';

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        parent::boot();
    }

    /**
     * Define the routes for the application.
     *
     * @return void
     */
    public function map()
    {
        $this->mapApiRoutes();

        $this->mapWebRoutes();
        // map〇〇Routesメソッドでルーティングをマッピング(展開)する
        $this->mapBatchRoutes();
    }

    /**
     * Define the "web" routes for the application.
     *
     * These routes all receive session state, CSRF protection, etc.
     *
     * @return void
     */
    protected function mapWebRoutes()
    {
        Route::middleware('web')
             ->namespace($this->namespace)
             ->group(base_path('routes/web.php'));
    }

    /**
     * Define the "api" routes for the application.
     *
     * These routes are typically stateless.
     *
     * @return void
     */
    protected function mapApiRoutes()
    {
        Route::prefix('api')
             ->middleware('api')
             ->namespace($this->namespace)
             ->group(base_path('routes/api.php'));
    }

    // 作成したルーティングファイルを書く
    /**
     * Define the "batch" routes for the application.
     *
     * These routes are typically stateless.
     *
     * @return void
     */
    protected function mapBatchRoutes()
    {
        Route::prefix('batch')
             ->middleware('batch')
             ->namespace($this->namespace)
             ->group(base_path('routes/batch.php'));
    }
}

補足

何やらRouteに色々くっつけて書かれてますね。
代表的なオプションメソッドの機能を書いておきます。

お好みで

種類 機能
prefix ルーティングURLの頭に共通のURLを付けられる
middleware ルーティングに共通のミドルウェア(前処理)を適用できる。ミドルウェアの設定はapp/Http/kernel.phpで行う
namespace 名前空間の定義(Contrllerを繋ぐ時のパスの起点を指定できる)
group ヒゲカッコ{}で囲んだルーティング群にオプションを一括して適用する。

Beforeの時点のRouteServiceProviderを見てみると、mapApiRoutesにはprefix('api')が付いてますね。
なので、api.phpに書かれたルートに繋ぐにはhomepage.jp/api/xxxxというURLで繋がるということが分かります。

web.phpとapi.phpの使い分け

もう一つ、自分が学びはじめに思った疑問「web.phpがあるのに、api.phpがあるのはなぜ?」という点について補足します。

端的にいうと「アプリケーションを管理しやすくするためにルーティングをファイル単位で分けているだけ」です。

webアプリケーションはblade(HTMLとDBなどから取得したデータ)を返すのに対し、
APIは一部のルーティングを除いて大多数のアクションはDBから取得したデータをJSONなどの形式で返却します(SPAアプリケーションに多い)。

実質的にはどちらも同じルーティングファイルなので、apiの処理をweb.phpに書いたりしても問題ありません。
(ただ、LaravelはApp\Http\kernel.phpに各ルーティングのミドルウェアを設定しているので、色々と設定の確認・編集が必要です)

まとめ

ユーザーと管理者の二面アプリケーションを作成する時なんかは、ファイル単位でルーティングも分けたくなります。
そういったケースがあったら試してみてください!

19
14
0

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
19
14