In a previous tip, I pointed out that string-backed enums are case-sensitive, even when your database isn't.
If your legacy data has "Active" and "ACTIVE" mixed in with "active", an enum cast throws a ValueError on anything that doesn't match exactly.
The fix I suggested was a one-time update to lowercase every value. That's still my first choice, but it isn't always practical. Maybe the table is huge and you don't want a long-running update in production. Or maybe an older system still writes to that table, and it keeps sending uppercase values.
In those cases, you can normalize the value in a custom cast instead:
class AccountStatusCast implements CastsAttributes
{
public function get(Model $model, string $key, mixed $value, array $attributes): AccountStatus
{
return AccountStatus::from(strtolower($value));
}
public function set(Model $model, string $key, mixed $value, array $attributes): string
{
return $value->value;
}
}
Then use it in place of the enum cast on your model:
protected function casts(): array
{
return [
'status' => AccountStatusCast::class,
];
}
Your code still gets an AccountStatus enum, no matter how the value was stored.
Notice I used from() and not tryFrom().
A value like "Active" should be normalized, but a value like "pending" is a real data problem.
tryFrom() would silently turn it into null, and I'd rather find out about that when it happens.
There's also a nice side effect. When a model is saved after the status has been read, the cast writes the lowercase value back to the database. So the data cleans itself up over time, one row at a time.
And queries keep working in the meantime.
where('status', AccountStatus::Active) still matches "ACTIVE" because of the case-insensitive collation.
Once the old data is cleaned up, and nothing is writing bad values anymore, you can swap back to a plain enum cast.
Here to help,
Joel
P.S. Modernizing an older Laravel app is full of small surprises like this. Schedule a call with Aaron to talk through how we can help you avoid them.