4

In Laravel 4.2 I had this before filter that set the Eloquent model and table based on the URL (admin.example.com vs example.com)

Here is my filter code:

App::before(function($request)
{       
  // Check if we are using the admin URL
  $host = $request->getHost();
  $parts = explode('.', $host);
  if ($parts[0] == 'admin')
  {
    // Set the config for user info (not sponsor)
    Config::set('auth.model', 'Admin');
    Config::set('auth.table', 'admins');
  }
});

I tried creating middleware for this in laravel 5 and have this code:

class AdminOrSponsor implements Middleware {

  public function handle($request, Closure $next)
  {   
    $host = $request->getHost();
    $parts = explode('.', $host);
    if ($parts[0] == 'admin'){
        Config::set('auth.model', 'Admin');
        Config::set('auth.table', 'admins');
    }

    return $next($request);
  }

}

In my routes.php file I am setting the controller that is called based on the auth.model setting like this:

Route::get('/auth/login', Config::get('auth.model') . 'Controller@getLogin');
Route::post('/auth/login', Config::get('auth.model') . 'Controller@postLogin');
Route::get('/auth/logout', Config::get('auth.model') . 'Controller@getLogout');

What I found is that the routes are all read prior to the middleware so the change I am trying to make through Config::set() isn't happening. I am only getting the value that is set in the auth.php config file.

What am I doing wrong and how should I do this in Laravel 5?

4

1 回答 1

1

您似乎想根据客户端的主机名加载不同的路由。

我理解您的解决方案,但它有点像 hack,当您想要对其进行单元测试时,您会遇到麻烦,如果您甚至可以让它工作。配置在路由之前加载,因此不可能根据请求设置路由,除非您依赖 $_SERVER (这也会破坏单元测试)。

我会做以下事情:

  1. 像这样创建路由:

    Route::get('/auth/login', 'AuthController@getLogin');
    Route::get('/auth/login/admin', 'AdminsController@getLogin');
    Route::get('/auth/login/sponsors', 'SponsorsController@getLogin');
    
  2. 创建一个中间件以防止赞助商访问 AdminsController,反之亦然。

  3. 在 AuthController 中auth/login,根据主机执行重定向到管理员或赞助商。

然后你只使用“标准”的 laravel 功能,你可以确定它不会引起任何奇怪的副作用。

于 2016-03-03T16:34:59.477 回答