Skip to content

Commit

Permalink
feat: Add uuid support. #47
Browse files Browse the repository at this point in the history
  • Loading branch information
overtrue committed Mar 8, 2024
1 parent abe8e6e commit 5768a40
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 3 deletions.
5 changes: 5 additions & 0 deletions config/versionable.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,9 @@
* The model class for user.
*/
'user_model' => \App\Models\User::class,

/**
* Use uuid for version id.
*/
'uuid' => false,
];
8 changes: 6 additions & 2 deletions migrations/2019_05_31_042934_create_versions_table.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,13 @@
public function up()
{
Schema::create('versions', function (Blueprint $table) {
$table->bigIncrements('id');
$uuid = config('versionable.uuid');

$uuid ? $table->uuid('id')->primary() : $table->bigIncrements('id');
$table->unsignedBigInteger(config('versionable.user_foreign_key', 'user_id'));
$table->morphs('versionable');

$uuid ? $table->uuidMorphs('versionable') : $table->morphs('versionable');

$table->json('contents')->nullable();
$table->timestamps();
});
Expand Down
10 changes: 10 additions & 0 deletions src/Version.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;

use function class_uses;
use function config;
Expand All @@ -35,6 +36,15 @@ class Version extends Model
'contents' => 'json',
];

protected static function booted()
{
static::creating(function (Version $version) {
if (\config('versionable.uuid')) {
$version->{$version->getKeyName()} = $version->{$version->getKeyName()} ?: (string) Str::orderedUuid();
}
});
}

public function user(): ?BelongsTo
{
$useSoftDeletes = in_array(SoftDeletes::class, class_uses(config('versionable.user_model')));
Expand Down
1 change: 0 additions & 1 deletion tests/FeatureTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@ public function it_can_create_version_with_diff_strategy()
$this->assertArrayHasKey('content', $post->lastVersion->contents);
$this->assertArrayHasKey('extends', $post->lastVersion->contents);


$post->update(['title' => 'version2', 'content' => 'version2 content', 'user_id' => 1234]);
$post->refresh();

Expand Down

0 comments on commit 5768a40

Please sign in to comment.