Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ligonsker's avatar

How to create record on pivot table when using factory?

I have a FileFactory and I made a factory for it. there also a pivot table with a many to many relationship called folder_file with a relationship between the folder and the file.

For my testing I want to update the pivot table with same folder_id and the created file_id from the factory.

So the folder is the same for all the files created.

The pivot table should look like that:

folder_id | file_id
----------|----------
     1    |     1
     1    |     2
     1    |     3
     1    |     4
     1    |     5

What is the correct way to do that? I don't want to create records in the folders table because it's only a single folder right now that is created when I seed the db.

I don't think I have to create a FolderFactory for this although it gives me errors when I try to use the has method: https://laravel.com/docs/9.x/eloquent-factories#many-to-many-relationships

Any better way to do it?

ty

0 likes
9 replies
tykus's avatar

I don't think I have to create a FolderFactory for this

How then do you get valid folder_id for the relationship?

1 like
Ligonsker's avatar

@tykus I currently have a factory only for the File, so I thought I could somehow do an insert to the pivot table from there (from the File factory), because I think that in the past I first created the model then put the instance of it in the return part of the factory, this way I had the newly created model with all the details, then I could create a new instance of another model in that factory (But a vague memory I might be wrong)

Because all I need is to simply insert new row to the pivot every time the factory creates 1 record

Arteguilherme's avatar

I think you need to use belongsToMany. Almost like this:

    public function posts()
    {
        return $this->belongsToMany(Category::class, 'post_categories', 'category_id',  'post_id');
    }
1 like
Ligonsker's avatar

@Arteguilherme I have this relationship in the models themselves, but not sure how to specify that I want to attach folder_id 1 to every File that the FileFactory creates

tykus's avatar
tykus
Best Answer
Level 104

@Ligonsker if you already have the Folder instance; then:

$folder->files()->attach(File::factory(5)->create());

You can shortcut the Folder and FIles creation in a single expression using:

$folder = Folder::factory()
    ->hasAttached(File::factory()->count(5))
    ->create();
1 like
Ligonsker's avatar

@tykus thank you, that was the correct way.

I first grabbed the folder in tinker: $folder = Folder::find(1); then did as you said. Next step would be to do the shortcut you mentioned and create it from the factory and not the seeder

Please or to participate in this conversation.