Development

Laravel auth middleware on specific resource routes only

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

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago