diff --git a/config/laravel_ticket.php b/config/laravel_ticket.php index cc63408..4f5c6ac 100644 --- a/config/laravel_ticket.php +++ b/config/laravel_ticket.php @@ -39,6 +39,7 @@ * @see https://laravel.com/docs/9.x/eloquent-relationships#one-to-many */ 'columns' => [ + 'user_foreing_id' => 'user_id', 'ticket_foreing_id' => 'ticket_id', ], ], diff --git a/database/migrations/create_messages_table.php.stub b/database/migrations/create_messages_table.php.stub index 51a1907..0a75417 100644 --- a/database/migrations/create_messages_table.php.stub +++ b/database/migrations/create_messages_table.php.stub @@ -15,7 +15,7 @@ return new class extends Migration Schema::create($tableName['table'], function (Blueprint $table) use ($tableName) { $table->id(); - $table->foreignId('user_id'); + $table->foreignId($tableName['columns']['user_foreing_id']); $table->foreignId($tableName['columns']['ticket_foreing_id']); $table->text('message'); $table->timestamps(); diff --git a/src/Models/Message.php b/src/Models/Message.php index c6a0989..fc78b62 100644 --- a/src/Models/Message.php +++ b/src/Models/Message.php @@ -38,6 +38,21 @@ public function ticket(): BelongsTo ); } + /** + * Get Message Relationship + * + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function user(): BelongsTo + { + $tableName = config('laravel_ticket.table_names.messages', 'message'); + + return $this->belongsTo( + config('auth.providers.users.model'), + $tableName['columns']['user_foreing_id'] + ); + } + /** * Get the table associated with the model. * diff --git a/tests/Feature/MessageTest.php b/tests/Feature/MessageTest.php index 22ab8f5..c94b7c6 100644 --- a/tests/Feature/MessageTest.php +++ b/tests/Feature/MessageTest.php @@ -2,6 +2,7 @@ use Coderflex\LaravelTicket\Models\Message; use Coderflex\LaravelTicket\Models\Ticket; +use Coderflex\LaravelTicket\Tests\Models\User; it('can attach message to a ticket', function () { $message = Message::factory()->create(); @@ -13,3 +14,15 @@ $this->assertEquals($message->ticket->title, 'Can you create a message?'); }); + +it('message can be associated to a user', function () { + $user = User::factory()->create([ + 'name' => 'Oussama', + ]); + + $message = Message::factory()->create(); + + $message->user()->associate($user); + + $this->assertEquals($message->user->name, 'Oussama'); +});