'Eloquent insert id with sequence next value
I would like to create a new record in a PostgreSQL database table with Laravel eloquent but the table id is not auto incremented and it's make my life more difficult.
Here is the sample structure:
CREATE TABLE billing (
id int8,
companyname varchar(255) NOT NULL,
...
PRIMARY KEY (id),
);
The id field isn't auto incremented and I can't change this. Furthermore I can't write triggers.
In Laravel I would like to do something like this:
$billing = new Billing;
$billing->id = DB::raw("nextval('sequence')");
$billing->companyname = $request->companyname;
// ...
$billing->save();
It's working but it seems messy.
How could I simplify the DB (id) part of my code?
Thanks!
Solution 1:[1]
Try with
$billing->id = DB::getPdo()->lastInsertId(); // + 1 ?
Solution 2:[2]
with this
$nextval=DB::select(DB::raw("SELECT nextval('".(new Billing())->getTable()."_id_seq') as seq"))[0]->seq;
$billing = new Billing;
$billing->id = $nextval;
$billing->companyname = $request->companyname;
// ...
$billing->save();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | John |