Skip to content

Instantly share code, notes, and snippets.

@SimonBarrettACT
Last active December 7, 2023 10:40
Show Gist options
  • Save SimonBarrettACT/aa782d73be14efd747003e79343b5caa to your computer and use it in GitHub Desktop.
Save SimonBarrettACT/aa782d73be14efd747003e79343b5caa to your computer and use it in GitHub Desktop.
A trait to enable use of Spatie Laravel Enums with Livewire 3
<?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