Laravel 5 Resourceful Routes Plus Middleware

LaravelLaravel 5RoutesLaravel RoutingLaravel Middleware

Laravel Problem Overview


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?

Laravel Solutions


Solution 1 - Laravel

In QuotesController constructor you can then use:

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

Reference: Controller middleware in Laravel 5

Solution 2 - Laravel

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']]);
});

Solution 3 - Laravel

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.

Solution 4 - Laravel

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

Solution 5 - Laravel

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'
        ]
    ]);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkilrizzyView Question on Stackoverflow
Solution 1 - LaravelMarcin NabiałekView Answer on Stackoverflow
Solution 2 - LaravelThomas ChemineauView Answer on Stackoverflow
Solution 3 - LaravelMohanndView Answer on Stackoverflow
Solution 4 - Laravelbar5umView Answer on Stackoverflow
Solution 5 - LaravelChargnnView Answer on Stackoverflow