From 1f36839ef53bc1273d77f02550c14dcea58b0e86 Mon Sep 17 00:00:00 2001 From: Kirk Bushell Date: Mon, 20 May 2024 12:23:08 +1000 Subject: [PATCH] Updated the Slug value object to be castable. --- src/Behaviours/Slug.php | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/src/Behaviours/Slug.php b/src/Behaviours/Slug.php index 84f34a5..5b19487 100644 --- a/src/Behaviours/Slug.php +++ b/src/Behaviours/Slug.php @@ -3,10 +3,12 @@ namespace Eloquence\Behaviours; use Hashids\Hashids; +use Illuminate\Contracts\Database\Eloquent\Castable; +use Illuminate\Contracts\Database\Eloquent\CastsAttributes; use Illuminate\Contracts\Support\Jsonable; use Illuminate\Support\Str; -class Slug implements Jsonable +class Slug implements Castable, Jsonable { /** * @var string @@ -71,4 +73,22 @@ public function toJson($options = 0): string { return $this->__toString(); } + + public static function castUsing(array $arguments): CastsAttributes + { + return new class implements CastsAttributes + { + public function get($model, string $key, $value, array $attributes): ?Slug + { + return null === $value ? $value : new Slug($value); + } + + public function set($model, string $key, $value, array $attributes): array + { + return [ + $key => null === $value ? $value : (string) $value + ]; + } + }; + } } \ No newline at end of file