Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent ORM Transactions

Tags:

php

laravel

The Eloquent ORM is quite nice, though I'm wondering if there is an easy way to setup MySQL transactions using innoDB in the same fashion as PDO, or if I would have to extend the ORM to make this possible?

like image 571
wesside Avatar asked Feb 27 '13 06:02

wesside


2 Answers

You can do this:

DB::transaction(function() {       // }); 

Everything inside the Closure executes within a transaction. If an exception occurs it will rollback automatically.

like image 67
Laurence Avatar answered Sep 23 '22 11:09

Laurence


If you don't like anonymous functions:

try {     DB::connection()->pdo->beginTransaction();     // database queries here     DB::connection()->pdo->commit(); } catch (\PDOException $e) {     // Woopsy     DB::connection()->pdo->rollBack(); } 

Update: For laravel 4, the pdo object isn't public anymore so:

try {     DB::beginTransaction();     // database queries here     DB::commit(); } catch (\PDOException $e) {     // Woopsy     DB::rollBack(); } 
like image 28
Jürgen Paul Avatar answered Sep 24 '22 11:09

Jürgen Paul