When developing an application, you always need to insert dummy data into the database for testing purpose. I guess you already know how to seed normal table. Seeding database is really easy in laravel using ModelFactory. Laravel use an awesome package called Faker. Today i’ll show you how to seed Many to Many relationships (pivot table) with existing IDs. Lets start…
We have two main tables (users and roles) and one pivot table (user_role). Seed users and roles table with some dummy data and now we need list of IDs from users and roles table to seed pivot table. We’ll use DB facade to get lists of IDS:


//Get array of ids
$userIds = DB::table('users')->lists('id');
$roleIds = DB::table('roles')->lists('id');

// role_user
foreach ((range(1, 20)) as $index) {
DB::table('role_user')->insert(
[
'role_id' => $roleIds[array_rand($roleIds)],
'user_id' => $userIds[array_rand($userIds)]
]
);
}

This is how the seeder file will look:

use Illuminate\Database\Seeder;

class demoSeeder extends Seeder
{
  public function run()
  {
    //Seed roles table with 20 entries 
    factory('App\Role', 20)->create(); 

    //Seed users table with 20 entries
    factory('App\User', 20)->create();

    //Get array of ids
    $userIds      = DB::table('users')->lists('id');
    $roleIds      = DB::table('roles')->lists('id');

    //Seed user_role table with 20 entries
    foreach ((range(1, 20)) as $index) 
    {
      DB::table('role_user')->insert(
        [
          'role_id' => $roleIds[array_rand($roleIds)],
          'user_id' => $userIds[array_rand($userIds)]
        ]
      );
     }

  }
}