Laravel 8 中 Route::filter 的替代方案是什么?
What is the alternative to Route::filter in Laravel 8?
除了 /index
和 /login
,我希望所有页面都需要登录。我试着这样解决它:
Route::filter('pattern: ^(index|login)*', 'auth');
在 laravel 8 Route::filter
中不再可用。如何在不将每个路由定义放入一个大组的情况下解决这个问题?
在您的 routes/web.php 文件中创建一个中间件组。
Route::middleware(['auth'])->group( function () {
// Your protected routes here
});
或者,您可以为路由设置中间件例外:
// In your auth middleware that extends Authenticate
...
/**
* Routes that should skip handle.
*
* @var array $except
*/
protected array $except;
public function __construct()
{
$this->except = [
route('index'),
route('login')
];
}
/**
* @param \Illuminate\Http\Request $request
*/
public function handle( Request $request )
{
$current_route = $request->route();
if( in_array($current_route, $this->except ) {
// Route doesn't need to be guarded
}
}
...
如果你不想有大的组,那么你可以为每个路由指定中间件(可能看起来很乱)
Route::get('/route', [FooController::class, 'index'])->middleware('auth');
除了 /index
和 /login
,我希望所有页面都需要登录。我试着这样解决它:
Route::filter('pattern: ^(index|login)*', 'auth');
在 laravel 8 Route::filter
中不再可用。如何在不将每个路由定义放入一个大组的情况下解决这个问题?
在您的 routes/web.php 文件中创建一个中间件组。
Route::middleware(['auth'])->group( function () {
// Your protected routes here
});
或者,您可以为路由设置中间件例外:
// In your auth middleware that extends Authenticate
...
/**
* Routes that should skip handle.
*
* @var array $except
*/
protected array $except;
public function __construct()
{
$this->except = [
route('index'),
route('login')
];
}
/**
* @param \Illuminate\Http\Request $request
*/
public function handle( Request $request )
{
$current_route = $request->route();
if( in_array($current_route, $this->except ) {
// Route doesn't need to be guarded
}
}
...
如果你不想有大的组,那么你可以为每个路由指定中间件(可能看起来很乱)
Route::get('/route', [FooController::class, 'index'])->middleware('auth');