0

I am trying to create a demo crud using a Laravel 5.3. I wrote a controller's method to handle the update . This method should always starts transaction, and always rollback the changes. So the changes never commit into the database.

Here is how my method looks like

public function update($id, Request $request)
{
    DB::beginTransaction();
    $this->affirm($request);
    $biography = Biography::findOrFail($id);
    $data = $request->all();
    $biography->update($data);

    Session::flash('success_message', 'Biography was updated! However, because this is a demo the records are not persisted to the database.');
    DB::rollBack();

    return redirect()->route('demo.index');
}

Unfortunately, the update still gets committed every time. How can I correctly begin a transaction and then roll back the changes?

Jaylen
  • 39,043
  • 40
  • 128
  • 221
  • Aren't you able to rollback after the commit? As i see you are getting the data from the db and updating using the eloquent queries. – PaladiN Jan 29 '17 at 04:15
  • I don't want to commit. I want to rollback. I am expecting to start a transaction and then rolling it back – Jaylen Jan 29 '17 at 04:17
  • I have tried and found the code is working as expected. Could you show me what was your output ? – PaladiN Jan 29 '17 at 04:39
  • What database are you using? If MySQL, which engine are you using? – patricus Jan 29 '17 at 06:50
  • if you want to rollback immediately after updating then why are you updating the record in the first place?, i didn't get it. rollback used when you are performing multiple related db operation and if one of them failed then all will be revert back automatically, i think you are not using it that way. – Haritsinh Gohil Dec 09 '19 at 11:48

1 Answers1

5

you can rollback in case the code that before commit throws an exception.

public function update($id, Request $request)
{
DB::beginTransaction();
try{
$this->affirm($request);
$biography = Biography::findOrFail($id);
$data = $request->all();
$biography->update($data);

Session::flash('success_message', 'Biography was updated! However, because this is a demo the records are not persisted to the database.');
//if there is not error/exception in the above code, it'll commit
DB::commit();
return redirect()->route('demo.index');
} catch(\Exception $e){
//if there is an error/exception in the above code before commit, it'll rollback
DB::rollBack();
return $e->getMessage();
}

}

you can check this answer and here is the documentation about transactions

Omar
  • 203
  • 3
  • 5