Run Code Only When Conditions Match Using Conditionable Trait in Laravel
Laravel’s Conditionable trait powers methods like when() and unless(). You can use it in your own classes to build clean, chainable conditional logic.
The Problem: Breaking Flow with Conditions
In Laravel, we love this:
$query->when($active, fn ($q) => $q->where('active', 1));
But in your own classes, you often go back to:
if ($active) {
$service->filterActive();
}
👉 Flow breaks. Code becomes inconsistent.
The Hidden Feature: Conditionable
Laravel internally uses the Conditionable trait to power when() and unless().
You can use it too.
🔹 Step 1: Add Trait to Your Class
use Illuminate\Support\Traits\Conditionable;
class OrderService
{
use Conditionable;
public function filterActive()
{
// logicreturn $this;
}
}
🔹 Step 2: Use when() Like Laravel
$service = (new OrderService())
->when($active, fn ($s) => $s->filterActive());
🔹 Real Project Example
$orders = (new OrderService())
->when($paidOnly, fn ($s) => $s->paid())
->when($recent, fn ($s) => $s->recent())
->get();
Now your service behaves like Query Builder.
🔹 Bonus: unless()
$service->unless($isAdmin, fn ($s) => $s->restrictAccess());
🔥 Why This Is Powerful
It helps you:
- Keep consistent API style
- Build fluent services
- Avoid breaking chains
- Write expressive code
🧠 When to Use It
Use Conditionable when:
- Building service classes
- Creating reusable logic layers
- Designing fluent APIs