Yes, it is possible to perform tasks inside a DB transaction and rollback in the middle. Your code example is a good start, but you need to make a few changes to ensure that the transaction is rolled back if the conditions for the optional insert are not met.
Here's an updated version of your code:
try {
DB::beginTransaction();
$insertId = DB::table('table1')->insertGetId([
// ...
]);
DB::table('table2')->insert([
// ...
]);
// Conditional insert:
if ($request->flag) {
$extra_data = DB::table('some_table')->select(...)->where(...)->get();
// filter and validate extra data
// if some data is not found for example, roll back everything like
if ($extra_data->column !== 'x') {
DB::rollback();
throw new \Exception('Extra data not found');
}
DB::table('table3')->insert([
// insert some parts of $extra_data
]);
}
DB::commit();
} catch (\Exception $e) {
DB::rollback();
}
The main change is that we're now throwing an exception if the conditions for the optional insert are not met. This ensures that the transaction is rolled back and an error message is displayed.
Note that you can customize the error message to suit your needs.