illuminate/conditionable
Add fluent, chainable conditional logic to Laravel objects. The Conditionable trait provides when/unless helpers to apply callbacks only when conditions are met, keeping pipelines and builders clean and readable without scattered if/else blocks.
illuminate/conditionable adds a when() method to any class that uses the Conditionable trait, enabling fluent conditional method chaining. To start:
composer require illuminate/conditionableuse Illuminate\Support\Conditionable;
class MyService {
use Conditionable;
}
return (new MyService)
->when($condition, fn($s) => $s->methodA())
->when(!$condition, fn($s) => $s->methodB());
$dto = new UserDto()
->when($isActive, fn($dto) => $dto-> setActive(true))
->when($role === 'admin', fn($dto) => $dto-> grantPermission('write'));
$queueable = (new Job())
->when(config('app.debug'), fn($j) => $j->onQueue('debug'));
unless() (optional helper): Some projects add unless() as a complement:
->unless($skipValidation, fn($s) => $s->validate())
when($condition, callable $callback) returns the original instance if $condition is false—not null. This enables chaining safely.$this (the instance), so avoid modifying external state directly; prefer returning modified copies or chaining.when() is added via trait, some IDEs may not infer return types correctly—annotate the trait usage or use @method in the class docblock:
/**
* @method self when(callable $callback)
*/
when() across many classes, define your own trait that uses Conditionable, then use that trait instead.Collection and LazyCollection already use Conditionable, so collect([...])->when(...) works out of the box.How can I help you explore Laravel packages today?