Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5. FirstorNew with several conditions

I want to add a product to the database if there isn't a product with the same product_name, brand, weight and volume.

Here is my code:

$product = Product::firstorNew(['product_name'=>$request->product)], ['brand'=>$reques->brand), ['weight'=>$request->weight], ['volume'=>$request->volume]);

$product->product_name = $request->product;
$product->brand = $request->brand;
$product->weight = $request->weight;
$product->volume = $request->volume;
$product->save();

This code doesn't check all the attributes but only the first one and if it matches the row is updated instead of adding a new one. For example, in the DB there is a product id=1, product_name='Milk', brand='Parmalat', weight='null', volume=1 and if I add product_name='Milk', brand='Unimilk', weight='null', volume=0.5 row with id=1 will be updated, but in this case I want to add a new row to the DB.

like image 513
Svetoslav Dimitrov Avatar asked Feb 06 '23 07:02

Svetoslav Dimitrov


1 Answers

It looks like your brackets are placed wrongly. Try this:

$product = Product::firstOrNew([
  'product_name' => $request->product,
  'brand' => $request->brand,
  'weight' => $reqeust->weight,
  'volume' => $request->volume,
]);
like image 146
Mikk Mihkel Nurges Avatar answered Feb 09 '23 20:02

Mikk Mihkel Nurges