简体   繁体   中英

How to rollback a transaction in Laravel 5.3?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM