Laravel DB :: transaction does not throw an exception

I have this little problem with Laravel 4.2 and DB :: transaction. I had a problem with rollback transactions, so I tried the simplest piece of code and put it in route.php for testing:

routes.php:

DB::transaction(function(){ $user = App::make("User"); $user->save(); throw new Exception("Should not create users"); }); ... ... ... Some other code here 

I'm just trying to create a user when closing a transaction, and after creating the user, I make an exception to force the transaction to roll back. My problem is that even you have thrown an exception, the transaction is not a rollback. I get a new user in the database every time I update the application. The same code works as on the local computer, but on the server that I plan to use to produce it, it just does not roll back the transaction. Do you have any idea why?

EDIT:

MySql Server: 5.1.73-cll - MySQL Community Server (GPLv2)

PHP server: PHP 5.4.30 (cli) (built: July 19, 2014 15:22:18)

Local PHP: 5.5.9

Local MySql: 5.6.16

The server is on CentOs, and the local computer is on Windows 7.

+8
database php mysql laravel
Jul 24 '14 at 23:26
source share
3 answers

So, I answer my question. InnoDb was not the default storage engine until MySql 5.5. In my case, MYISAM was the default storage engine and did not support transactions. What I needed to do was enable InnoDB in my installation of the CPanel MySQL server. Than I had to make sure that each of the tables in my migrations with Laravel was created using the InnoDB mechanism. I did this by adding:

  $table->engine = "InnoDB"; 

for each migration file. After all the tables have been configured using the InnoDB mechanism, the transactions work as intended.

+15
Jul 25 '14 at 2:48
source share

An alternative could be setting to

/config/database.php

change engine value from zero to InnoDB

 'mysql' => [ 'driver' => 'mysql', 'host' => env('DB_HOST', '127.0.0.1'), 'port' => env('DB_PORT', '3306'), 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', ''), 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', 'strict' => true, 'engine' => 'InnoDB', ], 
+7
Dec 12 '16 at 4:25
source share

If you use multiple databases in your project, you need to specify in which database you want to commit and roll back.

 DB::connection('name_of_database')->beginTransaction(); try { //Do something DB::connection('name_of_database')->commit(); } catch (Exception $e) { DB::connection('name_of_database')->rollback(); } 
0
Aug 30 '19 at 21:49
source share



All Articles