Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel one to many table seed is not seeded as expected

So I have a relationship table like this ERD. I’m using eloquent database relationship in laravel to manage the foreign key.

It worked, but the data added is skipping one row.

Like this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is how I seed the database.

    public function run(): void
    {

        User::factory()
        ->has(FavPlant::factory(),'fav_Plant')
        ->count(5)
        ->create();
        
        Plants::factory()
        ->has(FavPlant::factory(),'fav_Plant')
        ->count(5)
        ->create();

    }

How do I make the relation table have both user_id and plants_id simultaneously?

>Solution :

You seem to have a many-to-many relationship between users and plants through the FavPlant pivot table. You can set both user_id and plant_id at the same time as below.

public function run(): void
{
    $users = User::factory()
        ->count(5)
        ->create();

    $plants = Plants::factory()
        ->count(5)
        ->create();

    // Seed FavPlant pivot table with relationships
    foreach ($users as $user) {
        foreach ($plants as $plant) {
            FavPlant::factory([
                'user_id' => $user->id,
                'plants_id' => $plant->id,
            ])->create();
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading