/** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // check if transfer exists $transfer = Transfer::find($id); if ($transfer === null || $transfer->user_id != Auth::user()->id) { // stuff to pass into view $title = "Error"; $errmsg = "The transfer does not exist."; return view('errors.error', compact('errmsg', 'title', 'heading')); } // get the account's for updating $account_from = $transfer->from; $account_to = $transfer->to; // start new transaction DB::transaction(function () use($transfer, $account_from, $account_to) { // update account balances if ($account_from !== null) { $account_from->balance = round(($account_from->balance * 100 + $transfer->amount * 100) / 100, 2); } if ($account_to !== null) { $account_to->balance = round(($account_to->balance * 100 - $transfer->amount * 100) / 100, 2); } if ($account_from !== null) { $account_from->save(); } if ($account_to !== null) { $account_to->save(); } // delete transfer $transfer->delete(); }); // flash message session()->flash('flash_message', 'Transfer deleted successfully. Balances rolled back!'); // redirect to transfers return redirect()->route('transfers.index'); }