Search code examples
laraveleloquentsavelaravel-9

Laravel 9 - DB::rollBack() how to perform this 2 times?


So, tittle cover a lot of this. Mycode saving more than one item at one click. Lets say we saving recipe or prescription (you named it). It cover drugs that somebody needed. I want save it (items) in one click including Name of the drug store. And my problem is when at second loop (at detailed_drug) it got error, i need rollback first successfull drug at database.

My JSON :

{
  "drug_store" : "DRG-2022070001",
  "street" : "Mataram Street, Malioboro, Yogyakarta",
  "date" : "28-12-2022 12:16:58",
  "status" : "RECIPE",
  "detailed_drug" : // here detailed_drug
  [
    {
      "drug_id" : "ITM-00001",
      "drug_name" : "acyclovir capsule",
      "exp_date" : "2022-12-09",
      "qty" : "2"
    },
    {
      "drug_id" : "ITM-00001",
      "drug_name" : "amiodarone tablet",
      "exp_date" : "2022-10-19",
      "qty" : "5"
    }
  ]
}

(I already know how to save (drug store etc) but when got error (at detailed_drug) i want rollback previous successfull data at database)

DB::connection('db_name')->beginTransaction();
$detailedRecipe= []; //for drugs or items.
$countDetail = $request->detailed; // lets pretend we have 2 drugs.

for($i=0;$i<$countDetail;$i++){

   $data = new Recipe();
   $data->drug_name = $request->drug_name;
   ...
   (etc)
   ...
   $success = $data->save();

   if(!$success) {
      DB::connection('db_name')->rollBack();
       return response()->json(['success' => false,'message' => 'Error message ... ']);
   }
}

DB::connection('db_name')->commit();

Solution

  • Silly of me. I call wrong database name. DB::connection('database_A') suppose to be DB::connection('database_B').