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
There is a insertGetId method.
If you get in complex structure, better to use Eloquent.
Best thing that you need review docs :
http://laravel.com/docs/eloquent
If you take a look at
Illuminate\Database\ConnectionInterface
you can see how these functions are written. UnfortunatelyDB::insert()
returns a boolean fromPDOStatement::execute()
and there is noDB::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()
After saving the data into the DB you just call
$insertedId = $user->id;
where$user->save()
is called before the step.more info here
There is a
insertGetId()
method, as follows: