What is the Conditionable trait?
Illuminate\Support\Traits\Conditionable adds when() and unless() to any class that uses it. These methods let you branch logic conditionally while keeping a fluent method chain intact.
The source lives in
src/Illuminate/Conditionable/Traits/Conditionable.php. The Illuminate\Support\Traits\Conditionable namespace is an alias that points there.Basic usage
when() — execute when the condition is truthy
unless() — execute when the condition is falsy
unless() is the inverse of when(). The callback runs when the condition is falsy.
Why the chain continues
When the callback returnsnull, when() returns $this so the chain continues. When the callback returns a value, that value becomes the next item in the chain.
null), $this is returned instead.
Calling when() with no arguments — HigherOrderWhenProxy
Callingwhen() with zero arguments returns a HigherOrderWhenProxy. This lets you set the condition lazily.
when() with one argument returns a proxy that holds that value as the condition.
Passing a closure as the condition
When the first argument is a closure, the closure’s return value is used as the condition.The classic QueryBuilder pattern
Dynamic query building withwhen() is the most common use case.
Adding Conditionable to your own classes
Use the trait in any class to getwhen() and unless() for free.
Using when() with Mail and Notifications
when() is available in Mailable and Notification classes too.
when() vs tap()
Both look similar but serve different purposes.Next steps
Higher order messages
Learn how the
$collection->map->method() syntax works and how to use it in practice.