Better way of Seeding a Pivot Table Better way of Seeding a Pivot Table laravel laravel

Better way of Seeding a Pivot Table


You may try this (Assuming that you have already seeded roles):

$user = User::create(['id' => '1', 'username' => 'user', 'password' => 'pass']);$user->roles()->sync([1,2]); // array of role ids$user = User::create(['id' => '2', 'username' => 'user2', 'password' => 'pass2']);$user->roles()->sync([3,4]); // array of role ids

I've used [] instead of array(), if your PHP is prior to ver-5.4 then you should use array().


For testing purposes I use pretty simple and fast method like below.

Imagine we have users and categories with pivot table (this comes from JeffreyWay's generators btw):

<?php// Composer: "fzaninotto/faker": "v1.3.0"use Faker\Factory as Faker;class UsersTableSeeder extends Seeder {    public function run()    {        $faker = Faker::create();        foreach(range(1, 100) as $index)        {            User::create([                'username'   => $username = $faker->userName,                'email'      => $faker->email,                'password'   => Hash::make($username),                'account_id' => $index            ]);        }    }}// all other seeders look the same, so I paste just the code that matters:// Categories    foreach(range(1, 30) as $index)    {        Category::create([            'name' => $faker->word        ]);    }// pivot table    foreach(range(1, 50) as $index)    {        DB::table('category_user')->insert([            'category_id' => rand(1,30),            'user_id' => $faker->unique()->randomNumber(1, 100)        ]);    }


For n:m Relationships, where I need to attach random entries, I use this simple but efficient Seeder code, that only uses real ids:

    $faker = Faker\Factory::create();    $limit = 100;    for ($i = 0; $i < $limit; $i++) {        $newrow = *Yourmodel*::create ([            'email' => $faker->word . rand(0, 9999) . '@test.com' ,          ...        ]);        $ids = $faker->randomElements( \App\YourOtherModel::select('id')->get()->toArray(), rand(1,*3*) );        foreach($ids as $id) {            $newrow->*your_relationship*()->attach( $id );   }