Summer Sale! All accounts are 50% off this week.

jrdavidson's avatar

Model Factory of Pivot Table and Morphable Columns

I'm currently facing a problem where I"m trying to use a pivot table that has a morphable columns where I want to be able to pass in what the morphed object is without it creating the additional model in the definition method of the UserAttachmentsFactory.

How can this be accomplished also keeping in mind that if a media object isn't passed in then it will generate one?

$user = User::factory()->create();

Media::factory()
    ->has(
        UserAttachments::factory()->for($user),
        'user_attachment'
    )
    ->create();
<?php

namespace Database\Factories;

use App\Models\UserAttachment;
use App\Models\User;
use App\Models\Media;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\Factory;

class UserAttachmentFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = UserAttachment::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        $media = Media::factory()->create();

        return [
            'user_id' => User:factory(),
            'media_id' => $media->id,
            'media_type' => get_class($meda),
        ];
    }
}
```
0 likes
0 replies

Please or to participate in this conversation.