php 向 Laravel 路由添加多个中间件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40822882/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding multiple middleware to Laravel route
提问by user1032531
Per laravel doc, I can add the auth
middleware as follows:
每个laravel doc,我可以添加auth
中间件如下:
Route::group(['middleware' => 'auth'], function () {
Route::get('/', function () {
// Uses Auth Middleware
});
Route::get('user/profile', function () {
// Uses Auth Middleware
});
});
I've also seen middleware added as follows:
我还看到添加了如下中间件:
Route::group(['middleware' => ['web']], function() {
// Uses all Middleware $middlewareGroups['web'] located in /app/Http/kernel.php?
Route::resource('blog','BlogController'); //Make a CRUD controller
});
How can I do both?
我怎样才能做到这两点?
PS. Any comments providing insight on what the bottom four lines of code are doing would be appreciated
附注。任何提供有关底部四行代码正在做什么的见解的评论都将不胜感激
回答by krlv
To assign middleware to a route you can use either single middleware (first code snippet) or middleware groups (second code snippet). With middleware groups you are assigning multiple middleware to a route at once. You can find more details about middleware groups in the docs.
要将中间件分配给路由,您可以使用单个中间件(第一个代码段)或中间件组(第二个代码段)。使用中间件组,您可以一次将多个中间件分配给一个路由。您可以在文档中找到有关中间件组的更多详细信息。
To use both (single middleware & middleware group) you can try this:
要同时使用(单个中间件和中间件组),您可以尝试以下操作:
Route::group(['middleware' => ['auth', 'web']], function() {
// uses 'auth' middleware plus all middleware from $middlewareGroups['web']
Route::resource('blog','BlogController'); //Make a CRUD controller
});
回答by Anandan K
回答by Ahmad Baktash Hayeri
You could also do the following using the middleware
static method of the Route
facade:
您还可以使用外观的middleware
静态方法执行以下操作Route
:
Route::middleware(['middleware1', 'middlware2'])
->group(function () {
// Your defined routes go here
});
The middleware
method accepts a single string for one middleware, or an array of strings
for a group of middleware.
该middleware
方法接受一个中间件的单个字符串,或一组中间件的字符串数组。