MohammedAttya's avatar

get Ids for Insert bulk

I want to insert bulk on database and get rows id (first one, last one or all rows)

I tried insertGetId but it took only one row per time

Is there any way to get the query object of insert or run anonymous function with it to run $id = $query->getConnection()->getPdo()->lastInsertId($sequence); on it ?

0 likes
4 replies
MohammedAttya's avatar

I solved this problem using app('db')->getPdo()->lastInsertId() after insert so I got the last inserted id

Cronix's avatar

Be careful with that. It will be the last id inserted into the db, and not necessarily from "this batch" if other queries are running at the same time or just before you retrieve the last id. This is not dependable unless you're absolutely sure no other queries are running during this time.

2 likes
MohammedAttya's avatar

@Cronix this is the function that laravel using for insertGetId() and it is returning last inserted ID for current session

I had issue with getting the correct IDs I found that MySQL returning the first ID of bulk insetred rows (not the last one as I expected)

Cronix's avatar

@MohammedAttya This is no more safe than what I said earlier, but it would get you the last inserted id by just selecting the highest id from the table.

$id = YourModel::latest('id')->value('id');

again, if any other insert queries were run on the table in between your bulk insert and when you check it, it won't be accurate.

1 like

Please or to participate in this conversation.