now in my Controller it's look like this
assume that $available = [ 1,2,3,4 ]
for ($i=0; $i < 3; $i++) {
if($available < 3){
echo 'success';
$database->save();
}else{
echo 'error';
}
}
for ($i=0; $i < $count; $i++) {
$id_w = $request->input('idw');
$id_p = $request->get('id_p')[$i];
$qty = $request->input('quantity_box')[$i];
$available = $this->check_stock($id_w, $id_p, $qty);
DB::transaction(function () use ($warehouse_products_sell, $available) {
if($available > 0){
$warehouse_products_sell = New Warehouse_products_sell;
$warehouse_products_sell->id_w = $id_w = $request->input('idw');
$warehouse_products_sell->id_c = $request->get('id_c')[$i];
$warehouse_products_sell->id_p = $id_p = $request->get('id_p')[$i];
$warehouse_products_sell->quantity_box = $qty = $request->input('quantity_box')[$i];
$warehouse_products_sell->price = $request->input('price')[$i];
$warehouse_products_sell->serial_num = $a;
$available = $this->check_stock($id_w, $id_p, $qty);
echo 'success';
}else{
echo 'error';
throw new \Exception('Error');
}
});
}
You can use Transactions. Have a look here.
Your code will change to this
DB::transaction(function () use ($database, $available) {
for ($i=0; $i < 3; $i++) {
if($available < 3){
echo 'success';
$database->save();
}else{
echo 'error';
throw new \Exception('Error');
}
}
});
If any exception is thrown, it will automatically rollback.