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.
Using FTP and PHP to get an array of file details such as size and…
Creating and using Laravel form requests to create cleaner code, separation and reusability for your…
Improving the default Laravel login and register views in such a simple manner but making…
Laravel validation for checking if a field value exists in the database. The validation rule…