lesssugar lesssugar - 4 months ago 15
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

except
array:

class UserController extends Controller
{
public function __construct() {

// Exclude foo- and barAction from auth middleware
$this->middleware('auth', ['except' => [
'fooAction',
'barAction',
]]);
}
}


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?

EDIT:

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

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).