5

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?

Mihail Duchev
  • 4,691
  • 10
  • 25
  • 32
Vladimir Djukic
  • 2,042
  • 7
  • 29
  • 60
  • The MyISAM engine does not support Transactions. Every query is atomic. If you need transactions, your tables must be InnoDB or NDB, or some other engine that supports transactions. You may have found this question searching for Laravel mysql transactions, but the original supposition of the question can only be answered as "not possible unless you convert your tables to InnoDB" – gview Aug 14 '19 at 17:25

2 Answers2

17

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...
    }
E Steven
  • 81
  • 9
delatbabel
  • 3,601
  • 24
  • 29
  • 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? – Vladimir Djukic Feb 07 '16 at 15:44
  • for people still visiting this question, DB::rollBack(); should be with capital B – Roi Jan 24 '19 at 08:18
3

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.

Zsolt
  • 31
  • 1
  • 2