Home > Software engineering >  How to use inserted query id for running another query in Laravel
How to use inserted query id for running another query in Laravel

Time:12-28

I want to insert some data like this:

foreach($data as $arr){
    $query=DB::table('users');
    $query->insert([
          'usr_name' => $arr['mbr_mobile'],
          'created_at' => now()->toDateTimeString(),
          'updated_at' => now()->toDateTimeString(),
    ]);
    DB::table('members')->insert([
          'mbr_mobile' => $arr['mbr_mobile'],
          'mbr_usr_id' => $query['id'], // returns error
          'created_at' => now()->toDateTimeString(),
          'updated_at' => now()->toDateTimeString(),
    ]);
}

As you can see I tried inserting data into users table and then inserting data into members table.

But I do need the id of the row that data has just got inserted into users table, so I can use it for mbr_usr_id.

But this is wrong since it is showing me Cannot use object of type Illuminate\Database\Query\Builder as array error.

And if I write $query->id instead of $query['usr_id'], I get Undefined property error!

So how can I use inserted query id for running another INSERT query in Laravel?


UPDATE #1:

And if I do this, I get Call to a member function lastInsertId() on bool error:

$lastInsertedID = $query->insert([
       'usr_name' => $arr['mbr_mobile'],
       'usr_is_active' => 1,
       'usr_password' => bcrypt($arr['mbr_national_code']),
       'created_at' => now()->toDateTimeString(),
       'updated_at' => now()->toDateTimeString(),
])->lastInsertId();

DB::table('members')->insert([
       ...
       'mbr_usr_id' => $lastInsertedID,
]);

CodePudding user response:

Please try this

foreach($data as $arr){
    $user_id = DB::table('users')->insertGetId([
          'usr_name' => $arr['mbr_mobile'],
          'created_at' => now()->toDateTimeString(),
          'updated_at' => now()->toDateTimeString(),
    ]);
    DB::table('members')->insert([
          'mbr_mobile' => $arr['mbr_mobile'],
          'mbr_usr_id' => $user_id, 
          'created_at' => now()->toDateTimeString(),
          'updated_at' => now()->toDateTimeString(),
    ]);
}

CodePudding user response:

use this insertGetId here is the example how to use it

$id = DB::table('users')
->insertGetId(
[
    'usr_name' => $arr['mbr_mobile'],
    'created_at' => now()->toDateTimeString(),
    'updated_at' => now()->toDateTimeString(),
]);

CodePudding user response:

Use insertGetId instead insert. Or use Inserting & Updating via Models, there is an id getter

  • Related