mercredi 9 décembre 2020

how to work with laravel transaction rollback

I am trying to execute some queries which are dependant on each other, so what I want is if any error occurs then rollback all the queries inside transaction. what I've tried so far is


        DB::transaction(function () use($user,$token,$request) {
            $billing = User_billings::create([
                'users_id' => $user->id,
                'agent_id' => null,
                'purpose' => 'Some Purpose',
                'agent_token_id'=>$token->id,
                'amount' => $request->amount,
                'payment_method' => 'Agent Token',
                'status' => 1
            ]);


            if($billing){
                $user_jorunal = User_journal::create([
                    'bill2_id' => $billing->id, //Intentionally made this error to test transaction, this should be 'bill_id'
                    'u_id' => $user->id,
                    'purpose' => 'Topup via Agent Token',
                    'debit' => $billing->amount,
                    'invoice_number' => time()
                ]);
                if($user_jorunal){

                    if($this->agentTokenBalance($request->token_id) == 0){
                        $token->status=1;
                        $token->update();
                    }
                    return response()->json(['status'=>true,'message'=>'TopUp was Successful!']);
                }
            }
        });

so when I execute this query It generates an error as SQLSTATE[HY000]: General error: 1364 Field 'bill_id' doesn't have a default value, but it also creates a row on user_billings table. Can you please specify where I am wrong?

all of the above code is running fine, be sure that there is no logical error in query except the intentional one . I am using laravel 5.7 in this project

PHP version is 7.2.19

following laravel documentation



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire