Home > Software engineering >  Laravel get model ID before saving
Laravel get model ID before saving

Time:10-18

How can I get the ID for the next record so I can pass it to a custom payment gateway, and only save if the payment is successful?

So far, I create the transaction and pass the ID to the payment gateway. Unfortunately, this saves the transaction in the database even if the payment is unsuccessful.

public function makeDeposit($amount, Pool $pool, $payment_method_id, $payment_number, $user_id)
    {
        if ($payment_method_id === 1) {
            $deposit = Transaction::create([
                'pool_id' => $pool->id,
                'user_id' => $user_id,
                'amount' => $amount,
                'payment_method_id' => $payment_method_id,
                'transaction_type' => 'deposit',
            ]);

            $result = $this->depositWithCustomGateway("XMZDEP" . $deposit->id, $payment_number, $amount, "XMZDEP" . $deposit->id);

            if ($result->status == 200 || $result->status == 201) {
                return $deposit;
            } else {
                throw new TransactionException($result->response->output_ResponseCode . " - " . $result->response->output_ResponseDesc, $result->status);
            }
        }
    }

CodePudding user response:

A way to go about this would be to save the item, then get the id, After passing the ID to the gateway, if it is unsuccessful, you then delete it from the database. If it is successful, you just let it be. In CODE:

$deposit = Transaction::create([
                'pool_id' => $pool->id,
                'user_id' => $user_id,
                'amount' => $amount,
                'payment_method_id' => $payment_method_id,
                'transaction_type' => 'deposit',
            ]);


$transactionId = $deposit->id(); // you now have the id



// Now pass the id to your payment gateway and if unsuccessful, you delete it from the database

$deposit->delete();

  • Related