Transaction with Eloquent Laravel 5

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

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

This code is executed succesfuly, but I'm not sure if the transaction is working ... How can I check it?

+4
source share
2 answers

In fact, there are only two ways to do this, and not particularly nice, because DB: transaction does not report errors.

  • Place the try / catch block inside the closure and set the external variable in the catch block if the transaction fails.

  • Perform a manual transaction using DB :: beginTransaction and rollback / commit, again with an exception handler according to 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 ...
    }
+11
+2

Source: https://habr.com/ru/post/1627463/


All Articles