how to update if exist else insert in Laravel 6 mysql?
Laravel provide method updateOrCreate for that purpose. Laravel is very useful when we want to do basic operation. Suppose if we have a condition that we have to Insert a new record if not exist and update if exist, If we do this task in php based laravel framework then we have to put if-else condition But In Laravel 6 we have done this by using one single simple query.
If there's a product from Mobile to Electronics Item, set the warrenty to 2 years.If no matching model exists, create one.
$product = App\Product::updateOrCreate( ['item' => 'Mobile', 'descriptions' => 'Electronics Item'], ['warrenty' => 2] );
Insert a new record if not exist and update if exist, laravel eloquent
Syntax for inserting a new record if not exist and update if exist is:
$product = Product::firstOrNew(YOUR_ColumnName);
$product = Product::firstOrNew(array('name' => Input::get('item_name'))); $product->item = Input::get('foo'); $product->save();