diff --git a/src/StateCaster.php b/src/StateCaster.php index ab2899a..0eafbc0 100644 --- a/src/StateCaster.php +++ b/src/StateCaster.php @@ -3,10 +3,11 @@ namespace Spatie\ModelStates; use Illuminate\Contracts\Database\Eloquent\CastsAttributes; +use Illuminate\Contracts\Database\Eloquent\SerializesCastableAttributes; use Illuminate\Support\Collection; use Spatie\ModelStates\Exceptions\UnknownState; -class StateCaster implements CastsAttributes +class StateCaster implements CastsAttributes, SerializesCastableAttributes { /** @var string|\Spatie\ModelStates\State */ private string $baseStateClass; @@ -70,6 +71,19 @@ public function set($model, string $key, $value, array $attributes): ?string return $value::getMorphClass(); } + /** + * @param \Illuminate\Database\Eloquent\Model $model + * @param string $key + * @param mixed $value + * @param array $attributes + * + * @return mixed + */ + public function serialize($model, string $key, $value, array $attributes) + { + return $value instanceof State ? $value->getValue() : $value; + } + private function getStateMapping(): Collection { return $this->baseStateClass::getStateMapping(); diff --git a/tests/StateCastingTest.php b/tests/StateCastingTest.php index 4437bff..bdf006f 100644 --- a/tests/StateCastingTest.php +++ b/tests/StateCastingTest.php @@ -136,3 +136,9 @@ public function registerStates(): void expect($model->state->getField())->toEqual('state'); }); + +it('serializes to a value', function() { + $model = new TestModel(); + + expect($model->toArray()['state'])->toBe(StateA::class); +});