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

左心房为你撑大大i 提交于 2019-12-30 14:51:08

问题


My subdomains are

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

Using below code causing problem with first parameter in laravel controller,

> Route::group(array('domain' => '{account}.myapp.com'), function() {
> Route::get('/get_data/{id?}', 'DataController@getData');
> })

I am getting subdomain value(dev1,dev2,dev3) instead of $id value in controller in getData method.

How to update my code to allow all subdomain, without making subdomain as first parameter in each method of controller.

Please share your idea.


回答1:


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');
});


来源:https://stackoverflow.com/questions/37359981/allow-multiple-subdomain-in-laravel-without-making-subdomain-as-route-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!