$dbConnection = DB::connection('i_test');
$tableNames = [];
try {
$dbConnection->beginTransaction(); // Begin transaction for all files
foreach($validatedData['filesData'] as $key => $data){
// Generate table name
$tableNames[$key] = (($key == 'destination') ? $validatedData['gateway'].'_D' : $validatedData['gateway']) .'_'.$this->userService->user->id;
// Drop table if exists
if ($dbConnection->getSchemaBuilder()->hasTable($tableNames[$key])) {
$dbConnection->getSchemaBuilder()->drop($tableNames[$key]);
}
// Create table
$dbConnection->getSchemaBuilder()->create($tableNames[$key], function ($table) use ($data) {
foreach ($data['headerRow'] as $header) {
$table->string($header)->nullable();
}
});
// Batch insert data
$chunks = array_chunk($data['dataRows'], 1000);
foreach ($chunks as $chunk) {
$dbConnection->table($tableNames[$key])->insert($chunk);
}
}
$dbConnection->commit(); // Commit transaction for all files
return :response([
'statusCode' => 'TXN',
'status' => 'Files Uploaded Successfully',
'data' => $tableNames
]);
} catch (IlluminateDatabaseQueryException $e) {
// Rollback transaction on error
$dbConnection->rollBack();
// Check if the exception is due to a duplicate entry error
if (strpos($e->getMessage(), 'Duplicate entry') !== false) {
return response([
'statusCode' => 'ERR',
'status' => 'Duplicate Entry Error Encountered',
'internalCode' => $e->getMessage(),
]);
} else {
return response([
'statusCode' => 'ERR',
'status' => 'Error occurred while processing file upload',
'internalCode' => $e->getMessage(),
]);
}
}
I have place $dbConnection->beginTransaction(); outside loop or try and block, but still encounter same error code there is no active transaction
I need to insert multiple files records to mysql database, but if there is any error in any file i need to toll back all the table data