feat(attachments): add HasAttachments trait to manage attachment relationships

This commit is contained in:
2026-06-25 14:47:21 -03:00
parent 56b87f0c12
commit 6db98ddc1a
2 changed files with 23 additions and 3 deletions

View File

@@ -0,0 +1,18 @@
<?php
namespace App\Domains\Attachable\Models\Concerns;
use App\Domains\Attachable\Models\Attachment;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphMany;
trait HasAttachments
{
/**
* @return MorphMany<Attachment, Model>
*/
public function attachments(): MorphMany
{
return $this->morphMany(Attachment::class, 'attachable');
}
}

View File

@@ -20,9 +20,7 @@ class AttachmentTest extends TestCase
'dominio' => 'acme.com',
]);
$attachment = Attachment::query()->create([
'attachable_type' => $tenant->getMorphClass(),
'attachable_id' => $tenant->getKey(),
$attachment = $tenant->attachments()->create([
'path' => 'attachments/acme/logo.png',
'filename' => 'logo.png',
'type' => AttachmentType::Image,
@@ -32,14 +30,18 @@ class AttachmentTest extends TestCase
]);
$this->assertSame(AttachmentType::Image, $attachment->type);
$this->assertTrue($tenant->attachments->contains($attachment));
$this->assertDatabaseHas('attachments', [
'id' => $attachment->id,
'attachable_type' => $tenant->getMorphClass(),
'attachable_id' => $tenant->getKey(),
'type' => AttachmentType::Image->value,
]);
$freshAttachment = Attachment::query()->findOrFail($attachment->id);
$this->assertSame(AttachmentType::Image, $freshAttachment->type);
$this->assertTrue($freshAttachment->attachable->is($tenant));
}
public function test_it_requires_attachment_type(): void