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.
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,
]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With