'[Laravel model]How can I update when a specific duplicated data is existed. [Laravel]

I have a table .

Books
`id(PK),name, genre, publish_date(DATE_TIME)` 

I would like to make it update When a record with same genre and publish_date exists.

id(PK),name, genre, publish_date(DATE_TIME)

for example

1,iq84,fiction,2022-04-11

is existed.

when 1q84,fiction,2022-04-11 is saved then 2,1q84,fiction,2022-04-11 is created.

I would like to make it "1,1q84,fiction,2022-04-11"

How can I fix it? How should I change the table structure?

Save function

$book = new Book;
$book->name = "1q84";
$book->genre = 1;//fiction
$book->publish_date = '2022-04-01';
$book->save();
$bookStore = new bookStore;
$bookStore->bookId = $book->id;


Solution 1:[1]

You can use the updateOrCreate method. for your example you can do it like this :

Book::updateOrCreate(
    ['gener' => 1,'publish_date' => '2022-04-01'],
    ['name' => '1q84']
);

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 Muhannad Jaafari