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

Ligonsker's avatar

How to seed the relationship table?

Currently I have a loop to create records on both table1 and table2. But I need to get the last inserted ids from the tables in order to insert it to the relationship table. But how can I get the two id's? This is the current code:

        for ($i = 0; $i < 100; $i++) {
            $table1_name = fake()->name(100);
            DB::table('table1')->insert([
                'name' => $table1_name 
            ]);

            $table2_name = fake()->name(100);
            DB::table('table2')->insert([
                'name' => $table2_name
            ]);
    }

So I need to then insert the created id from table1 and table2 on the same iteration:

           // inside the for loop, under table2 insert:
            DB::table('table1_table2')->insert([
                'table1_id' => // last inserted table1 id,
			    'table2_id' => // last inserted table2 id
            ]);

How can I do that?

Ty!

0 likes
6 replies
Sinnbeck's avatar

@Ligonsker ok. You should get the id returned

$id1 = DB::table('table1')->insert([
                'name' => $table1_name 
            ]);
1 like
Ligonsker's avatar

@Sinnbeck From some reason it fills the relationship table with only '1's on both ids. Why? This is the current code:

        for ($i = 0; $i < 100; $i++) {
            $table1_name = fake()->name(100);
            $id1 = DB::table('table1')->insert([
                'name' => $table1_name 
            ]);

            $table2_name = fake()->name(100);
            $id2 = DB::table('table2')->insert([
                'name' => $table2_name
            ]);

            DB::table('table1_table2')->insert([
                'table1_id' => $id1,
			    'table2_id' => $id2
            ]);
    }

it's not updating the id value from some reason

Please or to participate in this conversation.