65

是否可以将中间件添加到资源丰富的路线的全部或部分项目中?

例如...

<?php

Route::resource('quotes', 'QuotesController');

此外,如果可能的话,我想将所有路由都放在中间件之外indexshow使用auth中间件。或者这是需要在控制器内完成的事情?

4

5 回答 5

117

QuotesController构造函数中,您可以使用:

$this->middleware('auth', ['except' => ['index','show']]);

参考:Laravel 5 中的控制器中间件

于 2015-02-25T20:49:46.577 回答
64

您可以将路由组与中间件概念结合使用:http: //laravel.com/docs/master/routing

Route::group(['middleware' => 'auth'], function()
{
    Route::resource('todo', 'TodoController', ['only' => ['index']]);
});
于 2015-03-02T11:22:21.233 回答
6

在带有 PHP 7 的 Laravel 中,多方法排除对我不起作用,直到写

Route::group(['middleware' => 'auth:api'], function() {
        
Route::resource('categories', 'CategoryController', ['except' => 'show,index']);
});

也许这对某人有帮助。

于 2017-11-23T05:12:58.680 回答
5

Laravel 8.x 更新

网页.php:

Route::resource('quotes', 'QuotesController');

在您的控制器中:

public function __construct()
{
        $this->middleware('auth')->except(['index','show']);
        // OR
        $this->middleware('auth')->only(['store','update','edit','create']);
}

参考:控制器中间件

于 2021-01-22T13:36:48.093 回答
1

一直在为 Laravel 5.8+ 寻找更好的解决方案。

这是我所做的:

将中间件应用于资源,您不希望应用中间件的那些除外。(这里索引和显示)

 Route::resource('resource', 'Controller', [
            'except' => [
                'index',
                'show'
            ]
        ])
        ->middleware(['auth']);

然后,创建除第一个之外的资源路由。所以索引和显示。

Route::resource('resource', 'Controller', [
        'only' => [
            'index',
            'show'
        ]
    ]);
于 2019-10-21T22:56:59.350 回答