Вопрос

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?

Это было полезно?

Решение

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')

Другие советы

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

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

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.

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".

Just use underlying PDO instance:

DB::connection()->getPdo()->lastInsertId();
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top