gpt4 book ai didi

Laravel 将中间件 "only"、 "except"选项应用于路由组

转载 作者:行者123 更新时间:2023-12-02 18:16:19 25 4
gpt4 key购买 nike

我想将中间件选项应用于我的路由而不是 Controller 本身的唯一原因是因为我想从相同的路由 PHP 文件构建路由组,如下所示,并且我想做这样的事情:

Route::prefix('api')
->middleware('api')
->middleware('auth:api', ['only' => ['store', 'edit', 'delete']])
->middleware('auth:api', ['except' => ['index', 'show']])
->namespace($this->namespace)
->group(base_path('routes/api.php'));
Route::prefix('web')
->middleware('api')
->middleware('auth', ['only' => ['store', 'edit', 'delete']])
->middleware('auth', ['except' => ['index', 'show']])
->namespace($this->namespace)
->group(base_path('routes/api.php'));

但是,显然,官方文档列出了您可以在路由中使用此方法拥有多个中间件:

route->middleware('middleware1', 'middleware2')

是否有办法将“仅这些方法”和“除了这些方法”应用于路由组?如果不是,是否有另一种方法可以在我的 Controller 中解决此问题,以便它们知道请求来自哪个路由组并相应地使用不同的中间件?

最佳答案

如果我正确理解你的问题,route groups (如评论中所建议的)是执行您所描述的操作的“官方”方式,特别是当您嵌套它们时。

Nested groups attempt to intelligently "merge" attributes with their parent group. Middleware and where conditions are merged while names, namespaces, and prefixes are appended. Namespace delimiters and slashes in URI prefixes are automatically added where appropriate.

您还可以向 group 方法提供一组选项:

// routes/api.php
$namespaces = [
'namespace1',
'namespace2',
'namespace3',
...
];

foreach ($namespaces as $namespace) {

Route::group(['namespace' => $namespace], function() {

Route::group([
'prefix' => 'api',
'middleware' => [
'api',
['auth:api', ['only' => ['store', 'edit', 'delete']]],
['auth:api', ['except' => ['index', 'show']]]
],
], function() {

// api controller methods here

});

Route::group([
'prefix' => 'web',
'middleware' => [
'api',
['auth', ['only' => ['store', 'edit', 'delete']]],
['auth', ['except' => ['index', 'show']]]
],
], function() {

// web controller methods here

});

});

}

但请注意,您可能需要重新排列数组顺序才能获得所需的效果:

Middleware are executed in the order they are listed in the array

关于Laravel 将中间件 "only"、 "except"选项应用于路由组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44757445/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com