F
Filament14mo ago
urbycoz

Is there a way to use Toggle component for yes/no strings instead of booleans?

For some reason the table I am using has an is_admin field where the values are not booleans but instead text saying "yes" or "no". When I try to save when I use.... Toggle::make('is_admin') ....I (understandably) get this error: Invalid text representation: 7 ERROR: invalid input value: "0" CONTEXT: unnamed portal parameter $1 = '...' update "user" SET "is_admin" = 0 WHERE "id" = 31 (Note: I realise the ideal solution would be to redesign the table but there would be a lot of refactoring involved which I don't have time for right now.)
Solution:
Just use a Laravel custom attribute in your model? something like: ```php public function getis_adminAttribute($value)...
Jump to solution
4 Replies
Solution
toeknee
toeknee14mo ago
Just use a Laravel custom attribute in your model? something like:
public function getis_adminAttribute($value)
{
return $value === 'yes' ? true : false;
}
public function getis_adminAttribute($value)
{
return $value === 'yes' ? true : false;
}
urbycoz
urbycozOP14mo ago
Awesome, thanks. In the end it looked like this: public function getCustomIsAdminAttribute() : int { return $this->is_admin== 'Y' ? 1 : 0; } public function setCustomIsAdminAttribute($value) { $this->attributes['is_admin'] = $value ? 'Y' : 'N'; }
toeknee
toeknee14mo ago
Fab
Alex Six
Alex Six14mo ago
For folks searching in the future: another possible solution if you don't want to go down the attribute route is to create a custom caster and have Laravel cast "Yes/No" to "true/false" automatically. Once the caster is created, it's as simple as adding it to your model's $casts property:
$casts = [
'is_admin' => YesNoBoolean::class,
];
$casts = [
'is_admin' => YesNoBoolean::class,
];
Want results from more Discord servers?
Add your server