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

Gamecock's avatar

Seed ManyToMany Relationship pivot table with custom data

These are my tables:

companies table:

| id | name    |
|----|---------|
| 1  | Apple   |
| 2  | Samsung |
| 3  | Huawei  |

countries table:

| id | name          |
|----|---------------|
| 1  | United States |
| 2  | Russia        |
| 3  | China         |

company_country table:

| company_id | country_id | barcode    |
|------------|------------|------------|
| 1          | 1          | 7y87weyf   |
| 1          | 2          | j09akx09a  |
| 1          | 3          | jhbcx87tz8 |
| 2          | 1          | 67z5cxz8   |
| 2          | 2          | t8ads86t   |
| 3          | 3          | ucyhcz97   |

Relationships:

Country Model:

public function companies()
{
     return $this->belongsToMany(Company::class);
}

Company Model:

public function countries()
{
     return $this->belongsToMany(Country::class);
}

Each company has its own barcode based on specific country.

I want to seed company_country pivot table with my own prepared static data. So I don't need factory.

How can I do that?

0 likes
1 reply
isa's avatar

You can place your static data into csv file, and then, in seeder, read that file, and seed tables with whatever you need.

Please or to participate in this conversation.