From a16264db8a82b817d371fe3226e0530d05a89f44 Mon Sep 17 00:00:00 2001 From: Quentin Gabriele Date: Fri, 23 Feb 2024 17:12:50 +0100 Subject: [PATCH] add uuid --- .../add_uuid_to_conversations_table.php.stub | 42 +++++++++++++++++++ src/Conversation.php | 13 ++++-- src/ConversationServiceProvider.php | 4 +- 3 files changed, 53 insertions(+), 6 deletions(-) create mode 100644 database/migrations/add_uuid_to_conversations_table.php.stub diff --git a/database/migrations/add_uuid_to_conversations_table.php.stub b/database/migrations/add_uuid_to_conversations_table.php.stub new file mode 100644 index 0000000..558d048 --- /dev/null +++ b/database/migrations/add_uuid_to_conversations_table.php.stub @@ -0,0 +1,42 @@ +uuid()->nullable(); + }); + + Conversation::all()->each(function (Conversation $conversation) { + $conversation->uuid = (string) Str::uuid(); + $conversation->saveQuietly([ + 'touch' => false + ]); + }); + + + Schema::table('conversations', function (Blueprint $table) { + $table->uuid()->nullable(false)->change(); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::table('conversations', function (Blueprint $table) { + $table->dropColumn('uuid'); + }); + } +}; diff --git a/src/Conversation.php b/src/Conversation.php index b1a03ae..8430de6 100644 --- a/src/Conversation.php +++ b/src/Conversation.php @@ -12,9 +12,11 @@ use Illuminate\Database\Eloquent\Relations\HasOne; use Illuminate\Database\Eloquent\Relations\MorphTo; use Illuminate\Foundation\Auth\User; +use Illuminate\Support\Str; /** * @property int $id + * @property string $uuid * @property Collection $users * @property ?int $owner_id * @property ?User $owner @@ -30,10 +32,7 @@ class Conversation extends Model { use HasFactory; - protected $fillable = [ - 'owner_id', - 'metadata', - ]; + protected $guarded = []; protected $casts = [ 'metadata' => AsArrayObject::class, @@ -41,6 +40,12 @@ class Conversation extends Model protected static function booted(): void { + static::creating(function (Conversation $conversation) { + if (empty($conversation->uuid)) { + $conversation->uuid = (string) Str::uuid(); + } + }); + /** * Cleanup pivot records * We choose to not use onCascade Delete at the database level for 3 reasons: diff --git a/src/ConversationServiceProvider.php b/src/ConversationServiceProvider.php index 24923a6..c52a06f 100644 --- a/src/ConversationServiceProvider.php +++ b/src/ConversationServiceProvider.php @@ -20,8 +20,8 @@ public function configurePackage(Package $package): void 'create_conversations_table', 'create_messages_table', 'create_conversation_user_table', + 'add_uuid_to_conversations_table', ]) - ->hasConfigFile() - ->runsMigrations(); + ->hasConfigFile(); } }