简体   繁体   中英

Laravel exit code when condition in a loop is not met

I am trying to loop through an array and meet a condition before submitting to database. The else block must not run if one item in the loop passes the condition, all must pass before it submits but the issue I'm having is that if one item passes, it submits and still returns the exception for the others. Here is my function

for($i = 0; $i < $item_count; $i++){
            switch ($fields['comment'][$i]) {
                case null:
                if($fields['qty_issued'][$i] != $fields['qty_received'][$i]){
                return redirect()->back()->withErrors(['Failed!', 'Please provide reason why you\' receiving a lesser quantity for  in the comment box!']);
                }else{
                #Receive voucher Items
                $received_items = ReceivedItems::create([
                'item_id' => $fields['item_id'][$i],
                'qty' => $fields['qty_received'][$i],
                'voucher_code' => $fields['voucher_code'],
                'comment' => $fields['comment'][$i],
                 ]);
               }
             break;

            default:
            #code.... 
            break;
            }

        }

As far as I understood, you want all of your data to be inserted into your database or none. If this is the case, I suggest using database transactions. The documentation for this can be found at https://laravel.com/docs/8.x/database#database-transactions

The code for this should look like

DB::beginTransaction(); //Begin transaction we can rollback or commit later
for($i = 0; $i < $item_count; $i++){
        switch ($fields['comment'][$i]) {
            case null:
            if($fields['qty_issued'][$i] != $fields['qty_received'][$i]){
                DB::rollBack(); //We don't want to save the changes we made before
                return redirect()->back()->withErrors(['Failed!', 'Please provide reason why you\' receiving a lesser quantity for  in the comment box!']);
            }else{
            #Receive voucher Items
            $received_items = ReceivedItems::create([
            'item_id' => $fields['item_id'][$i],
            'qty' => $fields['qty_received'][$i],
            'voucher_code' => $fields['voucher_code'],
            'comment' => $fields['comment'][$i],
             ]);
           }
         break;

        default:
        #code.... 
        break;
        }

    }
DB::commit(); //Everything succeeded and we can commit our changes to the database

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM