How about this?
DB::select('insert into mytable (field1, field2) values (?, ?) ON CONFLICT DO NOTHING returning "id"', [
$value1,
$value2
]);
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi all
I need to submit a query like:
insert into mytable (field1, field2) values (value1, value2) ON CONFLICT DO NOTHING RETURNING id
I tried to use insertOrIgnore() method but It build the query with only ON CONFLICT DO NOTHING; I tried to use insertGetId() method It build the query with only RETURNING id.
Is there a way to "chain" the two methods?
I also tried to build a raw insert:
DB::insert('insert into mytable (field1, field2) values (?, ?) ON CONFLICT DO NOTHING returning "id"', [
$value1,
$value2
]);
but It doesn't return the id; It returns only true or false.
Can someone help me?
This is the final solution using RAW query instead of Eloquent.
$myQuery = 'insert into mytable (field1, field2) values (value1, value2) ON CONFLICT DO NOTHING returning id; ';
$output = DB::select($myQuery);
if (!empty($output)) { // the record was inserted; get id
$pickId = $output[0]->id;
} else { // the record already exists; get id
$output = Mytable::where([
['field1', '=', 'value1'],
['field2', '=', 'value2'],
])->first();
$pickId = $output->id();
}
Please or to participate in this conversation.