Black Friday: the Laravel testing course is $149 instead of $249, through Dec 7. See the course →
logo

A newer method to clean up resourceful routes

Every little bit helps

Joel Clermont
Joel Clermont
2025-04-16

From our daily Laravel tips email. Get the next one in your inbox.

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.

Want a tip like this in your inbox every weekday?

Each one takes less than 2 minutes to read. Join 4,000+ Laravel developers who already get them.

email
No spam. Only real-world advice.
Toss a coin in the jar if you found this helpful.