Laravel 5 Resourceful Routes Plus Middleware

强颜欢笑 提交于 2019-11-30 10:37:59

问题


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?


回答1:


In QuotesController constructor you can then use:

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

Reference: Controller middleware in Laravel 5




回答2:


You could use Route Group coupled with Middleware concept: http://laravel.com/docs/master/routing

Route::group(['middleware' => 'auth'], function()
{
    Route::resource('todo', 'TodoController', ['only' => ['index']]);
});



回答3:


In laravel 5.5 with php 7 it didn't worked for me with multi-method exclude until I wrote

Route::group(['middleware' => 'auth:api'], function() {

Route::resource('categories', 'CategoryController', ['except' => 'show,index']);
});

maybe that help someone.




回答4:


Been looking for a better solution for 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'
        ]
    ]);


来源:https://stackoverflow.com/questions/28729228/laravel-5-resourceful-routes-plus-middleware

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!