kilrizzy
kilrizzy

Reputation: 2943

Laravel 5 Resourceful Routes Plus Middleware

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?

Upvotes: 69

Views: 69152

Answers (5)

Mohannd
Mohannd

Reputation: 1428

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.

Upvotes: 6

bar5um
bar5um

Reputation: 912

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

Upvotes: 6

Chargnn
Chargnn

Reputation: 151

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

Upvotes: 2

Thomas Chemineau
Thomas Chemineau

Reputation: 761

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

Upvotes: 66

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111829

In QuotesController constructor you can then use:

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

Reference: Controller middleware in Laravel 5

Upvotes: 120

Related Questions