user8663822 user8663822 - 3 years ago 150
MySQL Question

How can i check all data in loop before save into database

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';
}
}


this will output like success success success error

and it will save 3 success into database , how can i check if i've 1 error it wont save any data

now im using

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');
}
});
}

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download