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:
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”.
A drained and empty Kennington reservoir images from a drone in early July 2024. The…
Merrimu Reservoir from drone. Click images to view larger.
Some early September spring shots from a bushwalk, It is still too early for wildflowers.
I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…
If you ever needed a simple solution in Laravel to delete an entire directory and…
How to enforce only one user to register or be registered in a Laravel web…