Skip to content
OpenCloseEsc
Tips
  • Laravel
  • validation
  • enums

Validate and cast a status with one backed enum

Rule::enum() accepts only the enum's values, and an enum cast on the model gives you the case everywhere else, so the list of valid statuses lives in one place.

1 min read

Status strings tend to be duplicated: once in the validation rule, once in a constant, once in a migration comment. A backed enum is the single source.

enum OrderStatus: string
{
    case Pending = 'pending';
    case Paid = 'paid';
    case Shipped = 'shipped';
}
 
// Form request
'status' => ['required', Rule::enum(OrderStatus::class)],
 
// Model
protected function casts(): array
{
    return ['status' => OrderStatus::class];
}

The request rejects anything but the three values, $order->status is an OrderStatus case, and $order->status === OrderStatus::Paid reads as intended. Adding a case means adding one line.

Rule::enum() also takes ->only([...]) and ->except([...]) for a form that may set only some of them.