'Error: Unsupported operand types: Illuminate\Database\Eloquent\Collection - int

I have this code where i both insert data into a table as well as the data for arithmetic operation.

public function Repay (LoanApplication $loanApplication, transLog $transaction,  Request $request) {
    abort_if(!Auth()->user()->is_admin, Response::HTTP_FORBIDDEN, '403 Forbidden');
    
    
    $data['Loan_id']    = $loanApplication->id;
    $data['Cust_id']    = $loanApplication->cust_id;
    $data['trans_type'] = "Credit";
    $data['Amount']     = $request['Amount'];
    
    transLog::create($data);

    
    $transact = $transaction::where('Loan_id', $loanApplication->id);
    
    $curr_amount = $transact->Where('trans_type', '=', 'debit')->get('Amount');
    $curr_repayment = $transact->where('trans_type', '=', 'credit')->sum('Amount');
    $bals = $curr_amount - $curr_repayment;

    if($bals == 0){
        $loanApplication->update([
            'status_id' => 18
        ]);

        return view('admin.loanApplications.index', compact('loanApplication', 'transact'))->withMessage('Repayment Successful!');
    }

The create function is working but i get an error above at the line

$bals = $curr_amount - $curr_repayment;

Any idea why this is?



Solution 1:[1]

$curr_amount = $transact->Where('trans_type', '=', 'debit')->get('Amount');

The get() statement here always returns an array.

$curr_repayment = $transact->where('trans_type', '=', 'credit')->sum('Amount');

The sum() statement returns a number (int or float).

So obviously these 2 operands cannot be added together.

Also you should probably define $transact like so since you are abusing the $transaction variable as a query instance, while it seems to refer to a model:

 $transact = transLog::query()->where('Loan_id', $loanApplication->id);

(And also refactor your code to use CamelCase: TransLog)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Flame