我正在我的 Laravel 应用程序中试验中间件。我目前将它设置为在经过身份验证的用户的每条路线上运行,但是,我希望它忽略以 setup
URI 开头的任何请求。
这是我的 CheckOnboarding
中间件方法的样子:
public function handle($request, Closure $next)
{
/**
* Check to see if the user has completed the onboarding, if not redirect.
* Also checks that the requested URI isn't the setup route to ensure there isn't a redirect loop.
*/
if ($request->user()->onboarding_complete == false && $request->path() != 'setup') {
return redirect('setup');
} else {
return $next($request);
}
}
这在我的 route 是这样使用的:
Route::group(['middleware' => ['auth','checkOnboarding']], function () {
Route::get('/home', 'HomeController@index');
Route::get('/account', 'AccountController@index');
Route::group(['prefix' => 'setup'], function () {
Route::get('/', 'OnboardingController@index')->name('setup');
Route::post('/settings', 'SettingsController@store');
});
});
现在,如果我转到 /home
或 /account
,我会像您期望的那样被重定向到 /setup
。这最初导致了重定向循环错误,因此 & $request->path() != 'setup'
位于中间件中。
我觉得这是一种非常笨拙的方法,而且在 setup
之后显然不匹配任何东西,比如我创建的 setup/settings
路由。
有没有更好的方法让这个中间件在用户的所有路由上运行,同时设置某些路由应该免于此检查?
最佳答案
你所做的没有任何问题,但是,我建议将你的路线组分开,即:
Route::group(['middleware' => ['auth', 'checkOnboarding']], function () {
Route::get('/home', 'HomeController@index');
Route::get('/account', 'AccountController@index');
});
Route::group(['prefix' => 'setup', 'middleware' => 'auth'], function () {
Route::get('/', 'OnboardingController@index')->name('setup');
Route::post('/settings', 'SettingsController@store');
});
或者,为您的身份验证设置一个父组:
Route::group(['middleware' => 'auth'], function () {
Route::group(['middleware' => 'checkOnboarding'], function () {
Route::get('/home', 'HomeController@index');
Route::get('/account', 'AccountController@index');
});
Route::group(['prefix' => 'setup'], function () {
Route::get('/', 'OnboardingController@index')->name('setup');
Route::post('/settings', 'SettingsController@store');
});
});
这也意味着您可以删除中间件中的额外条件:
/**
* Check to see if the user has completed the onboarding, if not redirect.
* Also checks that the requested URI isn't the setup route to ensure there isn't a redirect loop.
*/
return $request->user()->onboarding_complete ? $next($request) : redirect('setup');
希望这对您有所帮助!
关于php - 将中间件应用于 Laravel 5.4 中除 `setup/*` 之外的所有路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43135138/