SJB
SJB

Reputation: 313

Transaction in laravel 5.1

Does the transaction in laravel works with only DB facade?. i want to know if it works with eloquent model; i.e. following code will have intended effect

DB::beginTransaction();

try {
    eloquentModel::query();
} catch (\Exception $e) {
    DB::rollback();
}

Upvotes: 0

Views: 562

Answers (1)

ijpatricio
ijpatricio

Reputation: 180

Yes, works both with DB facade and your Eloquent Models.

(As your example, the connection used will be the default, so you're ok.)

Don't forget to DB::commit(); when it's ok to commit!

Also, your database table engine must be support transactions, such as InnoDB.

Suggestion, you can also use the simpler, transaction method

DB::transaction(function () {

    eloquentModel::query();

});

Also, don't be afraid to test it out, just to increase your confidence level. Say, provoque an error, to see it work

DB::beginTransaction();

try {
    eloquentModel::query();
    eloquentModel::create(['field_not_exists' => 'will throw exception!']);
} catch (\Exception $e) {
    // DB::rollback(); // test with comment, and without comment, check DB for results ;)
}
DB::commit();

Happy coding!

Upvotes: 3

Related Questions