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?
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?
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).
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']);