laravel raw queries last_insert_id
Asked Answered
R

5

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?

Ramonaramonda answered 8/11, 2012 at 23:7 Comment(0)
A
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' => '[email protected]')
Awad answered 8/11, 2012 at 23:7 Comment(2)
at time of writing, this also works in lumen :) (so I presume Laravel 5.4 too)Fascicule
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.Norford
N
7

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

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

Norford answered 8/11, 2012 at 23:10 Comment(0)
S
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.

Seigel answered 4/8, 2014 at 15:39 Comment(1)
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.Seigel
R
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' => '[email protected]')); Note: The insert_get_id method expects the name of the auto-incrementing column to be "id".

Rica answered 15/2, 2013 at 1:14 Comment(0)
M
0

Just use underlying PDO instance:

DB::connection()->getPdo()->lastInsertId();
Maffa answered 3/8, 2019 at 17:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.