Transaction with Eloquent Laravel 5

12,182

Solution 1

There are really only 2 ways of doing this, neither are particularly nice, because DB::transaction doesn't report errors.

  1. Put a try/catch block inside the closure and set an external variable in the catch block if the transaction fails.

  2. Do a manual transaction, using DB::beginTransaction and rollback / commit, again with an exception handler, as per this example:

    DB::beginTransaction();
    try {
        $project = Project::find($id);
        $project->users()->detach();
        $project->delete();
        DB::commit();
        $success = true;
    } catch (\Exception $e) {
        $success = false;
        DB::rollBack();
    }
    
    if ($success) {
        // the transaction worked carry on...
    }

Solution 2

The question is quite old, but in my opinion there is no way to achieve transactions with MyISAM storage engine.

The most recent MySQL server version is 5.7, and the corresponding reference guide describes, that MyISAM storage engine does not support transactions.

https://dev.mysql.com/doc/refman/5.7/en/myisam-storage-engine.html

If I know correctly, begin, commit and rollback statements are accepted without errors, but the behavior is different than expected.

Share:
12,182
Vladimir Djukic
Author by

Vladimir Djukic

Updated on June 13, 2022

Comments

  • Vladimir Djukic
    Vladimir Djukic almost 2 years

    I am using MyISAM for MySQL and I want to use transaction here is my code:

    DB::transaction(function () {
        $project = Project::find($id);
        $project->users()->detach();
        $project->delete();
    });
    

    This code execute succesfuly but I am not sure that transaction works... How can I test it?

  • Vladimir Djukic
    Vladimir Djukic about 8 years
    I don't care about error reporting I just need to be sure that 2 queries always run together... Could you show me example with manual transaction?
  • Roi
    Roi about 5 years
    for people still visiting this question, DB::rollBack(); should be with capital B