Skip to content

Instantly share code, notes, and snippets.

@mknparreira
Last active August 12, 2021 22:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mknparreira/37dc55ea4c4e41a6e74f6bca097ef828 to your computer and use it in GitHub Desktop.
Save mknparreira/37dc55ea4c4e41a6e74f6bca097ef828 to your computer and use it in GitHub Desktop.
Lumen | How to use Transactions with multiple connections
        $cn = DB::connection('pgsql-private');
        $cn->beginTransaction();

        try {
            $create = $this->create([
                'fk_user_id' => $user_id,
            ]);

            if (! $create) {
                throw new \Exception('PaymentProof does not recorded');
            }

            $sync1 = $create->attachments()->sync(array_column($attachments, 'id'));
            if (! $sync1) {
                throw new \Exception('Attachment does not recorded');
            }

            $sync2 = $paymentProof->balances()->sync(array_column($balances, 'id'));
            if (! $sync2) {
                throw new \Exception('Balance does not recorded');
            }

            $cn->commit();

            return [
                'message' => 'Success',
                'error' => false,
            ];
        } catch (\Exception $e) {
            $cn->rollBack();

            return [
                'message' => 'Caught exception:'.$e->getMessage(),
                'error' => true,
            ];
        }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment