diff --git a/README.md b/README.md index 2cc4d6c..17df8fa 100644 --- a/README.md +++ b/README.md @@ -75,3 +75,11 @@ Test method `test_countries_with_team_size()`. --- +## Task 6. Polymorphic Attachments + +In the route `/attachments`, the table should show the filenames and the class names of Task and Comment models. Fix the `app/Models/Attachment.php` relationship to make it work. + +Test method `test_attachments_polymorphic()`. + +--- + diff --git a/app/Http/Controllers/AttachmentController.php b/app/Http/Controllers/AttachmentController.php new file mode 100644 index 0000000..9a0259d --- /dev/null +++ b/app/Http/Controllers/AttachmentController.php @@ -0,0 +1,15 @@ +id(); + $table->string('filename'); + $table->morphs('attachable'); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('attachments'); + } +} diff --git a/resources/views/attachments/index.blade.php b/resources/views/attachments/index.blade.php new file mode 100644 index 0000000..cb25f33 --- /dev/null +++ b/resources/views/attachments/index.blade.php @@ -0,0 +1,5 @@ + diff --git a/routes/web.php b/routes/web.php index 46819c3..6bbd0ed 100644 --- a/routes/web.php +++ b/routes/web.php @@ -28,3 +28,5 @@ Route::get('roles', [\App\Http\Controllers\RoleController::class, 'index']); Route::get('teams', [\App\Http\Controllers\TeamController::class, 'index']); Route::get('countries', [\App\Http\Controllers\CountryController::class, 'index']); + +Route::get('attachments', [\App\Http\Controllers\AttachmentController::class, 'index']); diff --git a/tests/Feature/RelationshipsTest.php b/tests/Feature/RelationshipsTest.php index 4bdc582..aa175c1 100644 --- a/tests/Feature/RelationshipsTest.php +++ b/tests/Feature/RelationshipsTest.php @@ -2,6 +2,7 @@ namespace Tests\Feature; +use App\Models\Attachment; use App\Models\Comment; use App\Models\Country; use App\Models\Role; @@ -104,4 +105,32 @@ class RelationshipsTest extends TestCase $response = $this->get('/countries'); $response->assertSee('avg team size 4'); } + + // TASK: polymorphic relations + public function test_attachments_polymorphic() + { + $task = Task::create(['name' => 'Some task']); + $comment = Comment::create([ + 'task_id' => $task->id, + 'name' => 'Some name', + 'comment' => 'Some comment' + ]); + Attachment::create([ + 'filename' => 'something.jpg', + 'attachable_id' => $task->id, + 'attachable_type' => Task::class + ]); + Attachment::create([ + 'filename' => 'something.pdf', + 'attachable_id' => $comment->id, + 'attachable_type' => Comment::class + ]); + + $response = $this->get('/attachments'); + $response->assertStatus(200); + $response->assertSee('something.jpg'); + $response->assertSee('something.pdf'); + $response->assertSee('Task'); + $response->assertSee('Comment'); + } }