Search code examples
phplaravelforeachlaravel-8foreach-loop-container

Laravel 8 - just save only last record in foreach loop


In Controller, I want to save data but when I tried with foreach loop, it just saves last records

foreach (Form_821_item::group_items as $item) {
        foreach ($item['code'] as $code) { 
                $items = IntersectingList::where('trial_id', $form_821->trial_balance_id)->where('account_code', 'like', $code . '%')->get();
                if ($items) {
                    foreach ($items as $item) {
                        $account_name = $item->account_name;
                        $account_code = $item->account_code;
                        if ($item->total_balance_debit != 0) {
                            $financial_statements = $item->total_balance_debit;
                            $total_cash += $item->total_balance_debit;
                        } else {
                            $financial_statements = $item->total_balance_credit;
                            $total_cash += $item->total_balance_credit;
                        }
                    }
                }
            }
        $data = new Form_821_item();
        $data->form_821_id = $form_821->id;
        $data->account_name = $account_name;
        $data->account_code = $account_code;
        $data->financial_statement = $financial_statements;
        $data->save();
    }

Any more advice?


Solution

  • You need to put your insert code inside the foreach

    foreach (Form_821_item::group_items as $item) {
        foreach ($item['code'] as $code) { 
                $items = IntersectingList::where('trial_id', $form_821->trial_balance_id)->where('account_code', 'like', $code . '%')->get();
                if ($items) {
                    foreach ($items as $item) {
                        $account_name = $item->account_name;
                        $account_code = $item->account_code;
                        if ($item->total_balance_debit != 0) {
                            $financial_statements = $item->total_balance_debit;
                            $total_cash += $item->total_balance_debit;
                        } else {
                            $financial_statements = $item->total_balance_credit;
                            $total_cash += $item->total_balance_credit;
                        }
                        $data = new Form_821_item();
                        $data->form_821_id = $form_821->id;
                        $data->account_name = $account_name;
                        $data->account_code = $account_code;
                        $data->financial_statement = $financial_statements;
                        $data->save();
                    }
                }
            }
        
    }