1

I want to store data in 5 tables directly. I store/save data in 4 tables with success, but I get an error in the last table. How do I rollback the records in the first 4 tables?

This is my controller

$booking = new Book();
$booking->date = Carbon::now();
$booking->unique_number = mt_rand(1, 999);
$booking->save();
$bookingDetail = new BookDetail();
$bookingDetail->book()->associate($booking);
$bookingDetail->qty = $request->qty;
$bookingDetail->event_id = $id;
$bookingDetail->price = $event->price;
$bookingDetail->subtotal = $bookingDetail->qty * $bookingDetail->price;
$bookingDetail->save();
$booking->total = $bookingDetail->subtotal + $booking->unique_number;
$booking->save();
$bookingConfirmation = new BookConfirmation();
$bookingConfirmation->book()->associate($booking);
$bookingConfirmation->save();
$bookingCompletion = new BookCompletion();
$bookingCompletion->book()->associate($booking);
$bookingCompletion->save();
$participants = explode(', ', $request->participant_name);
if(count($participants) === $bookingDetail->qty){
    foreach ($participants as $participant) {
        $bookingParticipant = new BookParticipant();
        $bookingParticipant->participant_name = $participant;
        $bookingParticipant->save();
    }
}else{
    echo '<script language="javascript">alert("Jumlah orang tidak sesuai")</script>';
}
CDspace
  • 2,639
  • 18
  • 30
  • 36
Jems
  • 1,666
  • 4
  • 20
  • 50
  • 2
    Possible duplicate of [Laravel: Using try...catch with DB::transaction()](https://stackoverflow.com/questions/22906844/laravel-using-try-catch-with-dbtransaction) – Maraboc Sep 21 '17 at 14:54

1 Answers1

2

You can rollback the transaction via the rollBack method:

DB::rollBack();

If you would like to begin a transaction manually and have complete control over rollbacks and commits, you may use the beginTransaction method on the DB facade:

DB::beginTransaction();

You can use try catch block so if any think goes wrong then in catch block you can roll back your transaction

DB::beginTransaction();
    try{
    here you can add your code to exicute and commit db transaction
    } catch (Exception $e) {
        DB::rollback();

    }

Ref: https://laravel.com/docs/5.5/database#database-transactions

Also already answered stack question here Laravel: Using try...catch with DB::transaction()

Vision Coderz
  • 8,257
  • 5
  • 41
  • 57