Ad

Laravel : Insert Or Update Record When Exists Using DB Facade

- 1 answer

is there any method for inserting new record or update when record exists in database using DB facade ?
Note: there is no model but only a controller , so using model related methods is impossible.my question is regards to query builder

Ad

Answer

The most straightforward approach is to look into your database's syntax for upserting. It will be different depending on the database and the specific situation, and may require defining a UNIQUE key of some kind.

Here is an example for MySQL:

INSERT INTO table (a,b,c) VALUES (1,2,3)
  ON DUPLICATE KEY UPDATE c=c+1;

By the way, the more idiomatic approach would be to define a model. Model's allow you to handle this situation more gracefully and (in many cases) prevent you from tying your code to a specific RDBMS.

Ad
source: stackoverflow.com
Ad