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 ->
There is a insertGetId()
method, as follows:
$dataset = array('column_id' => 1, 'name' => 'Dayle');
$column_id = DB::table('users')->insertGetId($dataset,'column_id');
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.
$id = DB::table('users')->insertGetId(
array('id' => 1, 'name' => 'Dayle Rees')
);
If you get in complex structure, better to use Eloquent.
Best thing that you need review docs :
http://laravel.com/docs/eloquent
A bit late with the answer but, I think for psql it's best to use native RETURNING id
The query that worked for me was:
DB::select(
DB::raw('insert into threads (created_at, updated_at) values (?, ?)
returning id'), [Carbon::now(), Carbon::now()]
);
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()