本文介绍了允许在laravel中使用多个子域而不将子域设置为路由变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的子域是

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

使用以下代码导致laravel控制器中的第一个参数出现问题,

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

我正在使用getData方法在控制器中获取子域值(dev1dev2dev3)而不是$id value.

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.

请分享您的想法.

推荐答案

由于您不想在控制器方法上使用{account}变量,因此可以在变量中定义路由并将其传递给每个子域组,这是示例:

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

编辑

如果您的子域是动态的,那么您可以使用middleware,创建类似以下内容的中间件:

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

Kernel.php

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

然后在routes.php

Route::group(['middleware' => 'subdomain'],  function () {
    Route::get('/get_data/{id?}', 'DataController@getData');
});

这篇关于允许在laravel中使用多个子域而不将子域设置为路由变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 01:20