All packages
Enums for Laravel
Conditional callbacks
The whenIs* methods run a callback only when the condition matches, with an optional default callback otherwise. Each returns the same case, so calls chain:
NewsCategory::HotNews
->whenIs(NewsCategory::HotNews, fn ($enum) => activate($enum))
->whenIsNot(NewsCategory::PrivateNews, fn ($enum) => publish($enum));
NewsCategory::HotNews->whenIsIn(
[NewsCategory::HotNews, NewsCategory::RegularNews],
fn ($enum) => notifySubscribers($enum),
fn ($enum) => archive($enum), // runs when the condition is false
);
NewsCategory::HotNews->whenIsNotIn(
[NewsCategory::PrivateNews],
fn ($enum) => index($enum),
);Signatures
whenIs(self $enum, Closure $callback, ?Closure $default = null): self
whenIsNot(self $enum, Closure $callback, ?Closure $default = null): self
whenIsIn(array $enums, Closure $callback, ?Closure $default = null): self
whenIsNotIn(array $enums, Closure $callback, ?Closure $default = null): self- The callback receives the case; its return value is ignored.
- The optional $default runs only when the condition is false; without it, a non-match is a no-op.
- Callbacks are typed as Closure — arrow functions, closures or first-class callables such as $this->notify(...).
- Every method returns the case itself, so chaining never changes the value you started with.
In a service
First-class callables keep branching logic in named methods:
use App\Enums\NewsCategory;
use App\Models\Article;
final class ArticlePublisher
{
public function handle(Article $article): void
{
$article->category
->whenIs(NewsCategory::HotNews, $this->pin(...))
->whenIsNotIn(
[NewsCategory::PrivateNews],
$this->announce(...),
$this->keepInternal(...),
);
}
private function pin(NewsCategory $category): void { /* ... */ }
private function announce(NewsCategory $category): void { /* ... */ }
private function keepInternal(NewsCategory $category): void { /* ... */ }
}Show your open-source love
This package is free and MIT-licensed. If it saves you time, a one-off donation or a Patreon membership keeps it maintained, tested and documented.
More ways to support, including cryptoBy donating, you agree to our donation terms.
Want this built into your product?
We integrate our packages into custom Laravel and AI builds. Tell us what you're working on and we'll reply within 48 hours.