39
34

More than 5 years have passed since last update.

Laravel 5.8 routesをサブドメインで分ける

Last updated at Posted at 2019-04-25

こちらはブログにも公開しています。

Laravelのプロジェクトを作成するとroutesディレクトリにweb.phpとapi.phpが分かれています。

これは RouteServiceProvider.php内で定義されています。

    public function map()
    {
        $this->mapApiRoutes();

        $this->mapWebRoutes();

        //
    }

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

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

mapApiRoutesでprefix('api')と指定しているので、http://example.com/api/以下はapiのルーティングが適用されるようになっています。

今回はサブドメインで切り替えたいので、Route::domainを使用します

    protected function mapApiRoutes()
    {
        Route::domain('api.example.com')
            ->middleware('api')
            ->namespace($this->namespace)
            ->group(base_path('routes/api.php'));
    }

routes/api.phpでテスト用に追加して確認をしてみます。

Route::get('/test', function(){
    echo "api";
});

https://api.example.com/testで"api"と返ってくれば成功です。

その他:ユーザーごとにサブドメインを分ける

ユーザーごとにサブドメインを分けている場合

https://[userId].example.com/のような場合は以下のようにします。

    public function map()
    {
        $this->mapApiRoutes();

        $this->mapWebRoutes();

        $this->mapUserRoutes();    // 追加
    }

    // 追加
    protected function mapUserRoutes()
    {
        Route::domain('{user}.'.config('const.app_domain'))
            ->middleware('web')
            ->namespace($this->namespace)
            ->group(base_path('routes/user.php'));
    }
Route::get('/test', function($user){
    return $user;
});

https://123.example.comで”123”と表示したら成功です。

39
34
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
39
34