- PHP
- enums
- validation
tryFrom() at the edges, from() inside
OrderStatus::from('xyz') throws a ValueError; tryFrom('xyz') returns null. Use tryFrom for query strings, webhooks and imports, and from where a wrong value is a bug.
1 min read
Both turn a raw value into a case. They differ only in what happens when the value is not one.
$status = OrderStatus::tryFrom($request->query('status')) ?? OrderStatus::Pending;
$status = OrderStatus::from($row['status']);The first line reads a filter from the URL: an unknown value falls back to a default instead of a 500. The second reads from your own database, where a value outside the enum is a bug you want to hear about, so ValueError is right.
A form request should not need either: Rule::enum(OrderStatus::class) rejects the value before your code runs.