diff --git a/src/Eloquent/Concerns/UsesUUID.php b/src/Eloquent/Concerns/UsesUUID.php index c2ac4c1..8e359e0 100644 --- a/src/Eloquent/Concerns/UsesUUID.php +++ b/src/Eloquent/Concerns/UsesUUID.php @@ -23,10 +23,7 @@ public static function bootUsesUUID(): void return; } - $model->setAttribute( - $model->getUuidName(), - static::generateUniqueUuid() - ); + $model->setUuid(static::generateUniqueUuid()); }); } @@ -61,6 +58,16 @@ public function scopeByUuid(Builder $query, $uuid): Builder throw new InvalidArgumentException('The UUID has to be of type string, array or null.'); } + /** + * @param string|UuidInterface $uuid + * + * @return Model + */ + public function setUuid($uuid): Model + { + return $this->setAttribute($this->getUuidName(), strval($uuid)); + } + public function getUuid(): ?string { return $this->getAttribute($this->getUuidName()); diff --git a/tests/UsesUuidTest.php b/tests/UsesUuidTest.php index e8efa15..7d9e00d 100644 --- a/tests/UsesUuidTest.php +++ b/tests/UsesUuidTest.php @@ -47,9 +47,8 @@ public function it_does_not_generate_uuid_on_creating_when_uuid_attribute_is_val { $uuid = Str::uuid()->toString(); - $post = PostUuidAttribute::create([ - 'uuid' => $uuid, - ]); + $post = new PostUuidAttribute(); + $post->setUuid($uuid)->save(); static::assertIsString($post->getUuid()); static::assertTrue(Uuid::isValid($post->uuid)); diff --git a/tests/database/migrations/2020_02_15_000000_create_posts_table.php b/tests/database/migrations/2020_02_15_000000_create_posts_table.php index 2d377e8..0f7776e 100644 --- a/tests/database/migrations/2020_02_15_000000_create_posts_table.php +++ b/tests/database/migrations/2020_02_15_000000_create_posts_table.php @@ -10,7 +10,7 @@ public function up(): void { Schema::create('posts', static function (Blueprint $table): void { $table->bigIncrements('id'); - $table->uuid('uuid'); + $table->uuid('uuid')->unique(); $table->timestamps(); }); }