In this episode, we dive into the new addition to Laravel: the Conditionable
trait on the Route object. If you're wondering what the Conditionable
trait even is, don't worry—we start with a quick intro and walkthrough.
We explore how this trait gives you access to the handy when()
method directly on routes, just like you may have seen elsewhere in Laravel. This lets you conditionally modify routes (like adding or removing middleware) in a clean, chainable way—no more ugly if statements.
To make this real, we run through two relatable scenarios. First, we show how to conditionally add a “production only” middleware, so you can keep your local environment clear of unnecessary stuff. You’ll see how to use when()
to keep your code tidy, instead of wrapping big conditionals inline.
Next, we look at rate limiting. It's super useful in production, but can be a pain during development. We use when()
again to only apply the throttle middleware when the app isn’t local, letting us develop without constant lockouts.
Best of all, this isn’t just for middleware—you can use when()
to tweak your routes however you want, based on any condition. The trait opens up loads of flexibility in your route definitions with minimal fuss. If you’re looking to clean up your route logic and avoid repeating yourself, this episode is packed with practical tips!