Last active
December 7, 2023 10:40
-
-
Save SimonBarrettACT/aa782d73be14efd747003e79343b5caa to your computer and use it in GitHub Desktop.
A trait to enable use of Spatie Laravel Enums with Livewire 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Enums\Traits; | |
trait WiredEnum | |
{ | |
/** | |
* Convert a Livewire value to a spatie enum instance. | |
* | |
* @param mixed $value The value from Livewire. | |
* @return static | |
*/ | |
public static function fromLivewire(mixed $value): static | |
{ | |
if (static::isEnumInstance($value)) { | |
return $value; | |
} | |
return static::from($value['value']); | |
} | |
/** | |
* Check if a value is an instance of the spatie enum class. | |
* | |
* @param mixed $value The value to check. | |
* @return bool | |
*/ | |
public static function isEnumInstance(mixed $value): bool | |
{ | |
return $value instanceof static; | |
} | |
/** | |
* Convert the enum instance to a Livewire-compatible value. | |
* | |
* @return array | |
*/ | |
public function toLivewire(): array | |
{ | |
return [ | |
'value' => $this->value | |
]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment