Laravel Transaction over two different servers / databases

I am making an application in Laravel. I need to update/insert or delete two different tables in two different databases on two different servers and I want to do it with transaction (If update in one database fails, the other will be rolled back.) I am using MySql databases.

Please give Laravel code.

1 answer

  • answered 2018-07-11 06:29 DigitalDrifter

    Wrap the queries in a transaction closure and set the connections:

    DB::transaction(function () {
        DB::connection('conn1')->table('table_1')->update(['column_1' => 1]);
        DB::connection('conn2')->table('table_2')->update(['column_2' => 2]);
    });
    

    Setup the connections in config/database.php:

    'connections' => [
        'conn1' => [
            'driver'    => 'mysql',
            'host'      => 'host1',
            'database'  => 'database1',
            'username'  => 'user1',
            'password'  => 'pass1'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ],
        'conn2' => [
            'driver'    => 'mysql',
            'host'      => 'host2',
            'database'  => 'database2',
            'username'  => 'user2',
            'password'  => 'pass2'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ],
    ],