Laravel 5 Resourceful Routes Plus Middleware

后端 未结 4 788
一生所求
一生所求 2020-12-13 05:38

Is it possible to add middleware to all or some items of a resourceful route?

For example...



        
相关标签:
4条回答
  • 2020-12-13 06:10

    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'
            ]
        ]);
    
    0 讨论(0)
  • 2020-12-13 06:18

    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']]);
    });
    
    0 讨论(0)
  • 2020-12-13 06:19

    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.

    0 讨论(0)
  • 2020-12-13 06:20

    In QuotesController constructor you can then use:

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

    Reference: Controller middleware in Laravel 5

    0 讨论(0)
提交回复
热议问题