Home > Blockchain >  How can I avoid repetition in this Laravel seeder created for a many-to-many relationship?
How can I avoid repetition in this Laravel seeder created for a many-to-many relationship?

Time:01-02

I am working on a blogging application in Laravel 8.

The application gives the users roles and permissions. There is a many-to-many relationship between roles and permissions. For seeding the roles_permissions table, I have a the RolesPermissionsSeeder seeder:

class RolesPermissionsSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
      RolesPermissions::create([
        'role_id' => '1',
        'permission_id' => '7',
      ]);

      RolesPermissions::create([
        'role_id' => '2',
        'permission_id' => '1',
      ]);

      RolesPermissions::create([
        'role_id' => '2',
        'permission_id' => '2',
      ]);

      RolesPermissions::create([
        'role_id' => '2',
        'permission_id' => '3',
      ]);
    }
}

The problem

As can be seen above, this chunk of code appears 3 times, with slight modifications:

RolesPermissions::create([
    'role_id' => '2',
    'permission_id' => '1',
]);

Using this instead did not work for me:

RolesPermissions::create([
    'role_id' => '2',
    'permission_id' => [1, 2, 3],
]);

Question

What is the easiest way to use one create statement for every role_id?

CodePudding user response:

  RolesPermissions::factory(['role_id' => '2'])
    ->count(3)
    ->sequence(
        ['permission_id' => 1],
        ['permission_id' => 2],
        ['permission_id' => 3],
    )
    ->create();

CodePudding user response:

You can use

$permissions = [1, 2, 3];
foreach ($permissions as $permission) {
    RolesPermissions::create([
        'role_id' => '2',
        'permission_id' => $permission,
    ]);
}

Or

$permissions = [1, 2, 3];
$role = Role::find(2);
$role->permissions()->saveMany($permissions);
  • Related