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:Jump to solution
Just use a Laravel custom attribute in your model?
something like:
```php
public function getis_adminAttribute($value)...
4 Replies
Solution
Just use a Laravel custom attribute in your model?
something like:
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';
}
Fab
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: