WithCast issues with Laravel Enum package? #63
Answered
by
rubenvanassche
designvoid
asked this question in
Q&A
-
I have the following:
and
But when I call
|
Beta Was this translation helpful? Give feedback.
Answered by
rubenvanassche
Jan 5, 2022
Replies: 2 comments 1 reply
-
Hi @designvoid, You're using a Eloquent cast, these types of casts are not compatible with the data package cast's. You can create your own |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
designvoid
-
there you go. <?php
namespace Support\Casts;
use Spatie\Enum\Laravel\Enum;
use Spatie\LaravelData\Casts\Cast;
use Spatie\LaravelData\Casts\Uncastable;
use Spatie\LaravelData\Support\DataProperty;
class EnumCast implements Cast
{
public function cast(
DataProperty $property,
mixed $value
): Enum|Uncastable
{
$enum = $this->type ?? $this->findType($property);
if ($enum === null) {
return Uncastable::create();
}
return $enum::from($value);
}
protected function findType(
DataProperty $property
): ?string
{
foreach ($property->types()->all() as $type) {
if (is_a($type, Enum::class, true)) {
return (string)$type;
}
}
return null;
}
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @designvoid,
You're using a Eloquent cast, these types of casts are not compatible with the data package cast's. You can create your own
EnumCast
fairly quickly, more information about that over here: https://spatie.be/docs/laravel-data/v1/advanced-usage/creating-a-cast