In Laravel 5 how do I implement an App::before() filter?

痴心易碎 提交于 2019-12-21 17:33:13

问题


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?


回答1:


It seems you want to load different routes depending on the client's hostname.

I understand your solution, but it is sort of a hack and you'll run into trouble when you want to unit test this, if you can even get it to work. The config is loaded before the routes, so setting routes based on the request is impossible, unless you rely on $_SERVER (which also breaks unittests).

I would do the following:

  1. Create the routes as such:

    Route::get('/auth/login', 'AuthController@getLogin');
    Route::get('/auth/login/admin', 'AdminsController@getLogin');
    Route::get('/auth/login/sponsors', 'SponsorsController@getLogin');
    
  2. Create a middleware to prevent access to the AdminsController by the sponsors, and vice-versa.

  3. Inside the AuthController, perform a redirect from auth/login to either admins or sponsors, depending on the host.

Then you are only using "standard" laravel features, and you can be sure that it doesn't cause any strange side-effects.



来源:https://stackoverflow.com/questions/28846443/in-laravel-5-how-do-i-implement-an-appbefore-filter

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