68

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?

Karl Hill
  • 12,937
  • 5
  • 58
  • 95
kilrizzy
  • 2,895
  • 6
  • 40
  • 63

5 Answers5

120

In QuotesController constructor you can then use:

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

Reference: Controller middleware in Laravel 5

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
66

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']]);
});
  • 2
    about a year old but since I'm trying to do the same shouldn't it be `Route::resource('todo', 'TodoController', ['except' => ['index']]);` to exclude only index from auth middleware? – Anadi Misra May 14 '16 at 17:17
  • It depends on what you want your auth controller on. The general idea is still relevant and so is the link provided, IMO. – dmcoding Jun 10 '21 at 19:06
6

In Laravel with PHP 7, it didn't work for me with multi-method exclude until wrote

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

maybe that helps someone.

Mohannd
  • 1,288
  • 21
  • 20
5

UPDATE FOR LARAVEL 8.x

web.php:

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

in your controller:

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

Reference: Controller Middleware

bar5um
  • 843
  • 1
  • 9
  • 21
2

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'
        ]
    ]);
Chargnn
  • 151
  • 11