简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM