lesssugar lesssugar - 1 year ago 93
PHP Question

Do I need to exclude all non-route actions from a Laravel controller middleware?

I'm using controller middlewares in my Laravel 5.2 app. According to the docs, to exclude specific actions from being handled by a middleware, I need to use the


class UserController extends Controller
public function __construct() {

// Exclude foo- and barAction from auth middleware
$this->middleware('auth', ['except' => [

Of course, the total number of methods in a controller will almost always be greater than the number of methods linked to specific routes in routes.php. So except for the route-actions there will be others, dealing strictly with the logic - public or private methods.

Do I need to exclude all those non-route actions from a middleware or excluding the route-actions is enough?


I would say that the other, non-route methods - as they are not accessible from outside - don't need to be excluded from a middeware. The question is rather: is the middleware ran for them every time they are accessed? I wouldn't say so but it's nice to make sure.

Answer Source

Your $this->middleware() method is defined in Illuminate\Routing\Controller: it merely saves its arguments in a protected property that is only accessed through a getter.

Other than in tests, that getter is only invoked in two places:

  1. Illuminate\Foundation\Console\RouteListCommand (which handles the route:list Artisan command); and

  2. Illuminate\Routing\ControllerDispatcher (which dispatches routing calls to a controller).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download