Apply an auth middleware to only certain routes in a Laravel resource route without needing to write out each route individually.
Generally a CRUD resource route looks like this in routes/web.php
Route::resource('photos', PhotoController::class);
Will give you these routes:
If you add the auth middleware onto the resource route they will only be accessible by logged-in (authenticated) users.
Route::resource('photos', PhotoController::class)->middleware(['auth']);
However what if you wanted the index and show to be accessible to anyone?
This can be done by using a construct in the route’s controller stating the middleware with an except clause listing the actions:
public function __construct() { $this->middleware('auth', ['except' => ['index', 'show']]); }
Here index and show can be viewed by anyone however create, store, edit, update and destroy will be protected by the auth middleware.
If you wanted to apply a middleware to certain routes rather than exclude it use “only” instead of “except”.