Allow multiple subdomain in laravel without making subdomain as route variable?

后端 未结 1 1908
独厮守ぢ
独厮守ぢ 2021-01-16 08:34

My subdomains are

domain1 = dev1.myapp.com,
domain2 = dev2.myapp.com,
domain3 = dev3.myapp.com
...

Using below code causing problem with fi

相关标签:
1条回答
  • 2021-01-16 08:58

    Since you don't want to use {account} variable on your controller methods, you can define your routes in a variable and pass it to each your subdomain group, here is the example:

    $subdomainRoutes = function () {
        Route::get('get_data/{id?}', function ($id) {
            //
        });
    };
    
    Route::group(['domain' => 'dev1.myapp.com'], $subdomainRoutes);
    Route::group(['domain' => 'dev2.myapp.com'], $subdomainRoutes);
    Route::group(['domain' => 'dev3.myapp.com'], $subdomainRoutes);
    

    EDIT

    If your sub domains are dynamic then you can use a middleware, create a middleware something like:

    namespace App\Http\Middleware;
    
    use Closure;
    
    class SubDomainAccess
    {
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
            $server = explode('.', $request->server('HTTP_HOST'));
            $subdomain = $server[0];
    
            // check if sub domain exists, replace with your own conditional check
            if (! Account::where('slug', $subdomain)->first()) {
                return abort(404); // or redirect to your homepage route.
            }
    
            return $next($request);
        }
    }
    

    Register your middleware in Kernel.php

    'subdomain' => \App\Http\Middleware\SubDomainAccess::class,
    

    Then use it on your routes.php

    Route::group(['middleware' => 'subdomain'],  function () {
        Route::get('/get_data/{id?}', 'DataController@getData');
    });
    
    0 讨论(0)
提交回复
热议问题