Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

aaronbains's avatar

Extend Query Builder Upsert()

I would like to write my own upsert() method for the query builder. I am not using any models or eloquent.

The upsert() method is found here: \Illuminate\Database\Query\Builder

How would I go about doing this? Where should I extend it and how can I then use it?

0 likes
5 replies
aaronbains's avatar

No I would not like to write it in raw SQL. I would just like to make some slight changes to the upsert method that ships with laravel framework. I would like to write my own upsert method, for example myUpsert(). So that I can call it by:

DB::table('orders')->myUpsert(....);

martinbean's avatar

@aaronbains Why? The query builder is meant to be a database abstraction layer. If you need something custom then write it; don’t start overriding core framework methods.

…or just create an Order model with your custom upsert method defined in it.

aaronbains's avatar

I will be more specific. I want to modify the upsert function to generate an alternate MySQL statement by adding this "id=last_insert_id" after ON DUPLICATE KEY in the MySQLGrammar file. So I need to modify the upsert function to accept a primary key argument so I can generate the correct SQL query.

Please or to participate in this conversation.