0

Hey All I am new to Laravel Eloquent.

I have a table called account id, that I need to write and update data.

when I try to update existing record it is working, However if the record not exists I need to add the record to the DB.

this is my code

AccountID::where('account_id', '=' ,$account_id) -> where('screen_type', '=', "ctv") -> update($update_account_ctv);
    
 AccountID::where('account_id', '=' ,$account_id) -> where('screen_type', '=', "app") -> update($update_account_app);
    
AccountID::where('account_id', '=' ,$account_id) -> where('screen_type', '=', "site") -> update($update_account_site);

How I can resolve this issue that will create a record if the record not exists

Bastian
  • 1,089
  • 7
  • 25
  • 74

1 Answers1

2

You can use updateOrCreate like this

TableA::updateOrCreate(
    ['account_id' => $account_id, 'screen_type' => 'ctv'],
    ['columnUpdate' => $data]
);

In the example below, if a flight exists with a departure location of Oakland and a destination location of San Diego, its price and discounted columns will be updated. If no such flight exists, a new flight will be created which has the attributes resulting from merging the first argument array with the second argument array:

$flight = Flight::updateOrCreate(
    ['departure' => 'Oakland', 'destination' => 'San Diego'],
    ['price' => 99, 'discounted' => 1]
);
Paul J.K
  • 603
  • 1
  • 4
  • 13