3

I'm using OctoberCMS and my rules is situated on model class. When occurs rules validation error, they throw new ModelException

trying:

DB::beginTransaction();
try 
{
  $model = new Model;
  $model->name = $name;
  $model->save();
 
  $another = new Another;
  $another->id = $model->id;
  $another->value = $value;
  $another->save();
  // all right
  DB::commit();
}
catch( ModelException $e ) 
{
  // some rules exception with one of these models
  DB::rollback();
}

Above code save the $model and if one ModelException is throw on saving $another, the $model record remains on database.

mysql: 5.6.21

tables: InnoDB

My workaround to make it work is:

    $model = new Model;
    $model->name = $name;
    $model->save();
    try 
    {
      $another = new Another;
      $another->id = $model->id;
      $another->value = $value;
      $another->save();
    }
    catch( ModelException $e ) 
    {
      $model->delete();
      $myerrors = $another->errors()->all();
    }

How make Laravel transactions work in described situation?

Community
  • 1
  • 1
Alexandre Thebaldi
  • 4,546
  • 6
  • 41
  • 55
  • You can do something like `$model->another()->associate($another)->save()` depending on the relationship. Doing this you can also drop `$model->save()`. – user2094178 Aug 15 '15 at 20:15

1 Answers1

6

You may try this:

DB::transaction(function()
{
    // Write your code here...
});

Note: Any exception thrown within the transaction closure will cause the transaction to be rolled back automatically. Laravel Website

Also you may read this, very nicely explained.

The Alpha
  • 143,660
  • 29
  • 287
  • 307
  • 2
    dude, i did read this article and all others on internet. this not worked for me using OctoberCMS and racked my brain. i give up transaction for now. but thanks :-) – Alexandre Thebaldi Aug 16 '15 at 03:35