Laravel 5 Resourceful Routes Plus 中间件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28729228/
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
Laravel 5 Resourceful Routes Plus Middleware
提问by kilrizzy
Is it possible to add middleware to all or some items of a resourceful route?
是否可以向资源丰富的路线的全部或部分项目添加中间件?
For example...
例如...
<?php
Route::resource('quotes', 'QuotesController');
Furthermore, if possible, I wanted to make all routes aside from index
and show
use the auth
middleware. Or would this be something that needs to be done within the controller?
此外,如果可能的话,我想将所有路由放在一边index
并show
使用auth
中间件。或者这是否需要在控制器内完成?
回答by Marcin Nabia?ek
In QuotesController
constructor you can then use:
在QuotesController
构造函数中,您可以使用:
$this->middleware('auth', ['except' => ['index','show']]);
Reference: Controller middleware in Laravel 5
回答by Thomas Chemineau
You could use Route Group coupled with Middleware concept: http://laravel.com/docs/master/routing
您可以将路由组与中间件概念结合使用:http: //laravel.com/docs/master/routing
Route::group(['middleware' => 'auth'], function()
{
Route::resource('todo', 'TodoController', ['only' => ['index']]);
});
回答by Mohannd
In laravel 5.5 with php 7 it didn't worked for me with multi-method exclude until I wrote
在带有 php 7 的 laravel 5.5 中,在我写之前,它对我没有用多方法排除
Route::group(['middleware' => 'auth:api'], function() {
Route::resource('categories', 'CategoryController', ['except' => 'show,index']);
});
maybe that help someone.
也许这有助于某人。
回答by Chargnn
Been looking for a better solution for Laravel 5.8+.
一直在为 Laravel 5.8+ 寻找更好的解决方案。
Here's what i did:
这是我所做的:
Apply middleware to resource, except those who you do not want the middleware to be applied. (Here index and show)
将中间件应用于资源,但不希望应用中间件的除外。(此处索引并显示)
Route::resource('resource', 'Controller', [
'except' => [
'index',
'show'
]
])
->middleware(['auth']);
Then, create the resource routes that were except in the first one. So index and show.
然后,创建除第一个之外的资源路由。所以索引和显示。
Route::resource('resource', 'Controller', [
'only' => [
'index',
'show'
]
]);