I have the following tables users , roles and the pivot table role_user with the following table structure
users
- id
- username
- password
roles
- id
- role
role_user
- id
- role_id
user_id
<?php class PivotTableSeeder extends Seeder { public function run() { // Seeds the roles table DB::table('roles')->delete(); DB::table('role_user')->insert(array( array('user_id' => 1, 'role_id' => 1), array('user_id' => 2, 'role_id' => 2), array('user_id' => 3, 'role_id' => 1), array('user_id' => 3, 'role_id' => 3), array('user_id' => 3, 'role_id' => 5) )); } }
The pivot table is seeded using DB select
Is there a better way to seed the tables, including the pivot table?
I was thinking maybe when I seed my users table, it will also seed the role_user table instead of manually inserting the data into the pivot table.
Example:
roles
- id = 1
- role = encoder
- id = 2
- role = tech
- id = 3
- role = sales
users
- id = 1
- username = user
- password = pass
- id = 2
- username = user2
- password = pass2
role_user
- id = 1
- user_id = 1
- role_id = 1
- id = 2
- user_id = 1
- role_id = 2
- id = 3
- user_id = 2
- role_id = 3
Edit
I am seeding my users table by using this Eloquent. Is there anyway that while seeding the User, the role_user will also get updated?
User::create(array(
'id' => '1',
'username' => 'user',
'password' => 'pass'
));
User::create(array(
'id' => '2',
'username' => 'user2',
'password' => 'pass2'
));