Muhammad Umar
Muhammad Umar

Reputation: 237

Insert record Many to Many relation in laravel at same time

I have three tables users,roles and role_user I want to insert record on that tables with minimum query using eloquent. My current code of insertation

User::create([
        'name' => 'admin',
        'email' => '[email protected]',
        'password' => bcrypt('admin123'),
    ]);

    //create default roles while installation of application
    $roles = array(
        array('name' => 'admin', 'display_name' => 'Administrator User', 'description' => 'system admin user'),
        array('name' => 'registered', 'display_name' => 'Registered User', 'description' => 'free user')
    );
    foreach ($roles as $key => $role)
    {
        Role::create($role);
    }

    //relation between users and roles

    User::find(1)->roles()->attach(1);

In above code i am creating a user then creating two roles then inserting record in pivot table(role_user). I want to know is there any otherway that i insert the record on these table at same time with one eloquent query Or there is anyother better way?

Upvotes: 4

Views: 1298

Answers (1)

Giedrius Kiršys
Giedrius Kiršys

Reputation: 5324

Unfortunately it is not possible to insert rows in more than one table at the same time.

Best what I can think of is that:

$user = User::create([
            'name'     => 'admin',
            'email'    => '[email protected]',
            'password' => bcrypt('admin123'),
        ]);

        //create default roles while installation of application
        $roles = [
            ['name' => 'admin', 'display_name' => 'Administrator User', 'description' => 'system admin user'],
            ['name' => 'registered', 'display_name' => 'Registered User', 'description' => 'free user']
        ];
        Role::insert($roles);

        //relation between users and roles
        $user->roles()->attach(1);

With this example You save two queries:

  1. Laravel calls only one insert query, instead of two when inserting roles;
  2. Laravel does not select User from database - using variable instead;

Upvotes: 1

Related Questions