Laravel DB::transaction not rolling back on exception

So I'm responding to my own question. InnoDb was not a default storage engine until MySql 5.5. In my case MYISAM was the default storage engine and did not support the transactions. What I had to do is enable InnoDB in my CPanel server installation of MySQL. Than I had to make sure each of the tables in my Laravel migrations was created with InnoDB engine. I did that by adding:

     $table->engine = "InnoDB"; 

to each migration file. Once all the tables were set up with InnoDB engine, transactions work as intended.


An alternative could be the settings in

/config/database.php

change value of engine from null to InnoDB

'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => 'InnoDB',
        ],

If you are using multiple databases on your project, you need to specify in which database you want to commit and rollback.

DB::connection('name_of_database')->beginTransaction();
    try {
        //Do something
        DB::connection('name_of_database')->commit();

    } catch (Exception $e) {
        DB::connection('name_of_database')->rollback();
    }