5

Is there a way to get the last_insert_id when using laravel's raw query?

DB::query('INSERT into table VALUES ('stuff') ')

This returns true or false. Is there a way to get last_insert_id using raw queries in Laravel?

Charles
  • 50,943
  • 13
  • 104
  • 142
Sinan
  • 5,819
  • 11
  • 39
  • 66

5 Answers5

18

Just the benefit of those who might have be having the same question for laravel 4, there is a slight syntax change from @haso-keric's response.

It is:

$id = DB::table('users')->insertGetId(array('email' => 'example@gmail.com')
Dele
  • 25
  • 1
  • 6
  • at time of writing, this also works in lumen :) (so I presume Laravel 5.4 too) – CodeMonkey Aug 03 '17 at 14:46
  • 1
    I wonder why was this accepted with all the upvotes, when question explicitly asked for raw queries. Though I agree that one really *shouldn't* use raw queries for this. – eis Mar 29 '19 at 20:07
7

Try DB::Query('SELECT LAST_INSERT_ID()')?

(this is DB product specific, example I've given is for MySQL/MariaDB.)

eis
  • 51,991
  • 13
  • 150
  • 199
3

For Laravel 4:

$id = DB::select('SELECT LAST_INSERT_ID()');

Explanation:

when using the lovely Laravel 4 PHP framework for websites etc, you should refer to the "DB::Select" function instead of "DB::Query" for raw queries. As "DB::Query" throws an error. I believe this is because its deprecated from v3, or plain doesn't exist. Yours, Smith.

Edmunds22
  • 715
  • 9
  • 10
  • when using the lovely Laravel 4 PHP framework for websites etc, you should refer to the "DB::Select" function instead of "DB::Query" for raw queries. As "DB::Query" throws an error. Yours, Smith. – Edmunds22 Aug 05 '14 at 16:53
2

Inserting a record that has an auto-incrementing ID? You can use the insert_get_id method to insert a record and retrieve the ID:

$id = DB::table('users')->insert_get_id(array('email' => 'example@gmail.com')); Note: The insert_get_id method expects the name of the auto-incrementing column to be "id".

Haso Keric
  • 271
  • 1
  • 5
0

Just use underlying PDO instance:

DB::connection()->getPdo()->lastInsertId();