There is no active transaction Error in creating table using Db Facade laravel

37 Views Asked by At
    $dbConnection = \DB::connection('test_connection');

    $dbConnection->beginTransaction();

    try{
            $dbConnection->getSchemaBuilder()->create('Alpha_1', function ($table) use ($validatedData) {
                $table->string('name')->nullable();
            });

            $dbConnection->commit();
        
    } catch (Exception $e) {

        // Rollback the transaction in case of error
        $dbConnection->rollBack();
        // Get the exact database error
        $errorMessage = $e->getMessage();
        
         dd($errorMessage);
    }

I want to know, why i am getting this error if creating db table with beginTransaction

2

There are 2 best solutions below

0
kris gjika On BEST ANSWER

From Mysql docs (https://dev.mysql.com/doc/refman/8.0/en/cannot-roll-back.html):

Some statements cannot be rolled back. In general, these include data definition language (DDL) statements, such as those that create or drop databases, those that create, drop, or alter tables or stored routines

0
Taranjeet Singh On

Remove those lines from the code

$dbConnection->beginTransaction();
$dbConnection->rollBack();

because in laravel database transactions are not supported for schema manipulation operations like creating or dropping tables. You can verify this information in the documentation