Yes, using a transaction is a good solution to ensure data integrity when inserting into multiple tables. Here's an example using Laravel's database query builder:
DB::beginTransaction();
try {
// Insert into orders table
$orderId = DB::table('orders')->insertGetId([
'user_id' => $userId,
'total' => $total,
// other order fields
]);
// Insert into details table
DB::table('details')->insert([
'order_id' => $orderId,
'product_id' => $productId,
'quantity' => $quantity,
// other details fields
]);
// Insert into coupons table
DB::table('coupons')->insert([
'order_id' => $orderId,
'code' => $code,
// other coupon fields
]);
DB::commit();
} catch (\Exception $e) {
DB::rollback();
// Handle the exception
}
In this example, we start a transaction using DB::beginTransaction(). Then we insert into the orders table and retrieve the inserted id using insertGetId(). We use this id to insert into the details and coupons tables. If any of the inserts fail, an exception will be thrown and we will roll back the transaction using DB::rollback(). If all the inserts succeed, we commit the transaction using DB::commit().