Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transaction with Eloquent Laravel 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?

like image 524
Vladimir Djukic Avatar asked Feb 05 '16 15:02

Vladimir Djukic


2 Answers

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...
    }
like image 113
delatbabel Avatar answered Oct 12 '22 18:10

delatbabel


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.

like image 45
Zsolt Avatar answered Oct 12 '22 19:10

Zsolt