TheJacol2017's avatar

Except method from middleware in route

Hello!

I wanna use middleware directly in the router, but except some methods, like 'show', 'index'. I tried with

<?php

...

Route::resource('/posts', 'PostsController') -> middleware('auth', ['except' => ['index', 'show']]);

...
?>

but it isn't working

route group and route::middleware don't work too...

I don't want to use middleware in each controller separately.

Thanks!

0 likes
2 replies
bobbybouwmann's avatar

You currently can't do that in the routes file. You can however do something like this

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

Route::resource('post', 'PostsController', ['only' => ['index', 'show']]);
2 likes
ruslanmr25's avatar

@TheJacol2017

I think You can write "middleware except method" in controller __constructor method like this

public function __construct(){
        $this->middleware('auth')->except('index');
    }

Please or to participate in this conversation.