Tuesday, March 14, 2017

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!



via Tamás Mazuk

Advertisement