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
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.
insert(...) returns the row id of the new inserted record.
There is a insertGetId method.
$id = DB::table('users')->insertGetId( array('id' => 1, 'name' => 'Dayle Rees') );
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With