Laravel 5 Resourceful Routes Plus Middleware
Solution 1
In QuotesController
constructor you can then use:
$this->middleware('auth', ['except' => ['index','show']]);
Reference: Controller middleware in Laravel 5
Solution 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']]);
});
Solution 3
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
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
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'
]
]);
kilrizzy
Updated on July 05, 2022Comments
-
kilrizzy almost 2 years
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
andshow
use theauth
middleware. Or would this be something that needs to be done within the controller? -
kilrizzy about 9 yearsThanks! Wasn't sure if this was something that could be done within the resource call but doesn't seem to be from what I've looked at so far
-
activatedgeek almost 9 yearsI need to pass other arguments to the Middleware, is it possible from this?
-
Marcin Nabiałek almost 9 years@activatedgeek If you have new question, ask one
-
Anadi Misra almost 8 yearsabout 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? -
trainoasis over 3 yearswhat about when using Route::apiResources([]) ? did not find how to add a middleware for all apiResources at once?
-
dmcoding almost 3 yearsIt depends on what you want your auth controller on. The general idea is still relevant and so is the link provided, IMO.