Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return new id with DB::insert() in Laravel 4

In Laravel 4, when you perform a DB::insert(), how can you get the ID of the row that has just been inserted? Similar what we have with the function ->insertGetId(). Reason for using DB::insert() is that its a complex PostgreSQL query that cannot be built using Fluent.

Example Query:

$newId = DB::insert('insert into users (id, name) values (?, ?)', array(1, 'Dayle')); echo $newId; // returns 1 
like image 420
Nyxynyx Avatar asked Apr 05 '13 19:04

Nyxynyx


People also ask

How can I get ID after insert in laravel?

Using getPDO() Method You can also use the PDO Object to get the last inserted id of a table in Laravel. Firstly you will have to insert the record and right after that, you can call the lastInsertId() method on the PDO object.

What does DB insert return?

insert(...) returns the row id of the new inserted record.


2 Answers

There is a insertGetId method.

$id = DB::table('users')->insertGetId(     array('id' => 1, 'name' => 'Dayle Rees') ); 
like image 119
Blessing Avatar answered Oct 03 '22 08:10

Blessing


If you take a look at Illuminate\Database\ConnectionInterface you can see how these functions are written. Unfortunately DB::insert() returns a boolean from PDOStatement::execute() and there is no DB::insertGetId() at the moment. If this would be useful then you should request it on GitHub.

In the mean time, you should be able to use DB::getPdo()->lastInsertId()

like image 31
Phill Sparks Avatar answered Oct 03 '22 07:10

Phill Sparks