skip to Main Content

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?

2

Answers


  1.   RolesPermissions::factory(['role_id' => '2'])
        ->count(3)
        ->sequence(
            ['permission_id' => 1],
            ['permission_id' => 2],
            ['permission_id' => 3],
        )
        ->create();
    
    Login or Signup to reply.
  2. 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);
    

    Edit

    To update without updated_at and created_at user insert()

    $permissions = [1, 2, 3];
    foreach ($permissions as $permission) {
        DB::table('roles_permissions')->insert([
            'role_id' => '2',
            'permission_id' => $permission,
        ]);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search