logo
podcast Podcast
get help Get Unstuck

A newer method to clean up resourceful routes

Every little bit helps

Joel Clermont
Joel Clermont
2025-04-16

Most of my applications are built with resourceful routes. If something doesn't fit nicely into one of the pre-defined resourceful methods, I'll usually split it into a separate invokable controller.

I like the consistency of this approach, and it also means that my routes file is nice and tidy as well.

One place that I would occasionally have to split up a resourceful controller's routes is when a particular middleware only applied to some of the routes.

I couldn't just chain ->middleware(SomeMiddleware::class) to Route::resource() because it would apply to all the routes. I'd have to split it up just to apply a different set of middleware.

But not too long ago, during the Laravel 11 release cycle, a new middlewareFor method was introduced so you can selectively apply middleware to just some methods in a resourceful route:

Route::resource('addresses', AddressController::class)
    ->middlewareFor('destroy', SomeSpecialMiddleware::class);

Now I don't have to split out the destroy route, but I can still apply that special middleware to just that resourceful method.

If I have additional methods with their own middleware, I can chain those on as well.

You probably won't need this a lot, but it's very handy to know it's there when you do.

Here to help,

Joel

P.S. Ever wonder if your Laravel app could be more secure? Download our free book for 7 steps to review.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice you can use.