Replace Long if-else Chains in Laravel Using PHP Match Expressions

Write cleaner business logic with modern PHP and Laravel.

  • 12 Jun, 2026
  • 35 Views

Replace Long if-else Chains in Laravel Using PHP Match Expressions

In many Laravel projects, business logic often looks like this:

if ($order->status === 'pending') {
    $label = 'Waiting for Payment';
} elseif ($order->status === 'paid') {
    $label = 'Paid';
} elseif ($order->status === 'cancelled') {
    $label = 'Cancelled';
} else {
    $label = 'Unknown';
}

It works.

But as statuses grow, readability decreases.


The Cleaner Alternative

Use PHP's match expression:

$label = match ($order->status) {
    'pending' => 'Waiting for Payment',
    'paid' => 'Paid',
    'cancelled' => 'Cancelled',
    default => 'Unknown',
};

Real Project Example

Imagine generating badge colors for orders:

$badgeColor = match ($order->status) {
    'pending' => 'warning',
    'paid' => 'success',
    'failed' => 'danger',
    default => 'secondary',
};

Blade:

<span class="badge bg-{{ $badgeColor }}">
    {{ $order->status }}
</span>

Why It's Better Than switch

switch ($status) {
    case 'paid':
        return 'success';
}

With match:

  • No break
  • No accidental fall-through
  • Returns values directly
  • More readable

Share: