TextColumn throwing an exception for the empty ENUM value
I have an attribute called
language
that is often used in several tables and for now 3 language codes could be used as values.
So, I created an Enum class App\Enums\Language
and in the Eloquent model the attribute language
is cast correctly:
In the related Filament Resource I have a dropdown field for the form:
And a text column for the list table:
As the result, on the Edit
and Create
pages the dropdown shows available labels from the Enum class and everything works as it should.
But the problem that some of the existing records don't have a value for the attribute language
.
And as the result, on the List
page an exception is throwing with the message "" is not a valid backing value for enum App\Enums\Language
.
I found a lot of related articles but still wasn't able to fix it. For example this one https://www.answeroverflow.com/m/1184219387109068871
Here https://medium.com/@yihen_26052/the-magic-from-method-of-enum-in-php-8-1-ad5a1a8f9298 also there is a good explanation between Enum ::from()
and ::tryFrom()
methods.
It seems that method tryFrom
returns null
for invalid values instead of throwing an exception. Maybe this could be a good fix for such case and could be fixed in the upcoming Filament version?
Or probably there is some workaround to avoid the error?
I would also be grateful if you could suggest what else could be used to move the repeating code into one place.
I know about the option of creating a separate table for languages in the database and linking it to the existing records. But for now I would like to put the list of languages in some PHP class.Nullable PHP Enum in Table TextColumn Oddity - Filament
I have a model/table that is a collection of various statuses (PHP Enum values) that are nullable if it's never been set.
When using a TextColumn like so:
If the field actually has an...
Medium
The Magic “from” method of Enum in PHP 8.1
In PHP 8.1, the enums i.e enumerations are introduced as a language feature. The feature comes with a few built in methods and one of the…
4 Replies

Ideally, a field based on an enum wouldn’t be an empty string. But you can use ->getStateUsing() on the text column to check if it’s empty and return early.
Or provide a default in the enum for getLabel() to return an empty string.
Thank you for your reply, I will try playing with
->getStateUsing()
.
Using the default
in the enum for getLabel()
didn't help for me.
I used such code:
Hmm, I would expect that to work.
There might also be an ->enum() modifier on the text column too, but not 100% on that.