I'm really concerned about my transaction with a database and my code structure. I have created more methods to insert, update, delete data to the database but sometimes some of them will break or miss. That's why I try to use Laravel transaction and PHP catch and throw exceptions to rollback and avoid any errors happening during those method processes.
By they way, I don't yet understand how try
/catch
and Laravel transaction catch those errors and return or throw to the end user.
However, I've tried to find all kind of errors will happen and how I can throw those error types to the end users in the catch
block.
This function work find but I want to check if any errors happen and how I can return those type of errors to the end user by using Laravel transaction and try
.
public function Dosomething($id)
{
if (Request::ajax()) {
$data = [
'till_account_id' => Request::input('till_account_id'),
'from_account' => Request::input('from_account'),
'to_account' => Request::input('to_account'),
'till_user_id' => Request::input('till_user_id'),
'branch_id' => Request::input('branch_id'),
'operate_by' => Request::input('operate_by'),
'type' => Request::input('type'),
'tranx_time' => date('Y-m-d H:m:s', time())
];
DB::beginTransaction();
try {
$update = Teller::where('id', '=', $id)->update(['balance' => Request::input('balanceCommision')]);
if (!empty($update)) {
$data['cash_out'] = Request::input('cash_out');
$trans_cashIn = DB::table('till_transaction')->insertGetId($data);
$data['cash_in'] = Request::input('cash_in');
$data['cash_out'] = 0;
$trans_cashOut = DB::table('till_transaction')->insertGetId($data);
}
$test = DB::commit();
return ['up' => $update, 'insCashIn' => $trans_cashIn, 'insCashOut' => $trans_cashOut, 'data' => $data, 'cash_out' => $data['cash_out'],'commit'=>$test];
} catch (Exception $e) {
DB::rollBack();
throw $e;
}
}
}