0

I am inserting bulk insertions in laravel 5 like this:

$data = array(
    array('name'=>'Jack', 'age'=>'24'),
    array('name'=>'Tom', 'age'=>'37'),
    //...
);

Users::insert($data);

Any idea how to get last inserted id?

Mr.Happy
  • 2,639
  • 9
  • 40
  • 73
  • The easiest way ... $data = array( array('name'=>'Jack', 'age'=>'24'), array('name'=>'Tom', 'age'=>'37'), //... ); foreach($data as $user){ $u = Users::create($user); $u->save(); $lastId = $u->id; } echo $lastId; – Hop hop Apr 22 '16 at 11:06
  • Just to clarify, are you wanting the very last inserted id or all the ids for the inserted data? – Rwd Apr 22 '16 at 13:44

2 Answers2

0

So, you can't use insertGetId() when bulk inserting data. So if you want to keep DB integrity, you could do something like this:

$lastRow = array_pop($data); // Cutting off last item from an array

Users::insert($data);
$lastId = Users::insertGetId($lastRow);

I know this is pretty dumb solution and it will create 2 queries instead of one, but if you'll not find anything better, you could use it.

Alternative

You could also try this:

$lastId = DB::select('select last_insert_id()');

This could work and it shouldn't brake DB integrity:

For LAST_INSERT_ID(), the most recently generated ID is maintained in the server on a per-connection basis. It is not changed by another client. It is not even changed if you update another AUTO_INCREMENT column with a nonmagic value (that is, a value that is not NULL and not 0).

Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
-1

You can both way

Using Eloquent Model

$user = new Reports();        
$user->email= 'johndoe@example.com';  
$user->save();
$lastInsertId = $user->id;

Or

Using Query Builder

 $lastInsertId = DB::table('reports')->insertGetId(['email' => 'johndoe@example.com']);