Categories: 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…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago