0

how to use Sql Transaction in this code sample. i tried but transaction is not working properly. my database engine is InnoDB.

 DB::transaction(function() use($request  ) {
 $user = User::$request->only('name','mobile','address');
 $userSave = User::create($user)->id;

 foreach ( $request->subjects as $items)
 {

  $data = User::$request->only('name');
   $data['student_id'] = $userSave
    $subject= Subject::create($data);

   }
  } //sql transaction end

I can not explain this better way .. so please read code and correct it. if i am wrong. problem is, it is not rollback if subject model query gone failed.

pankaj
  • 1
  • 17
  • 36
  • You need to be using `InnoDB` or `TokuDB` storage engine for rollback to work. Your code looks ok, and if it's not rolling back - it's most likely due to you using `MyISAM`. Can you confirm which engine is being used? – Mjh Jul 11 '17 at 10:36
  • yes ,, i am using InnoDB engine ... in my view ,problem is model area.. means i am not creating any object for Subject model.so that problem is coming.. may be not sure. – pankaj Jul 14 '17 at 21:59

1 Answers1

1

you forgot to DB::commit();

Without this your code will not work.

You should write DB:commit after foreach() statement

 DB::transaction(function() use($request  ) {
 $user = User::$request->only('name','mobile','address');
 $userSave = User::create($user)->id;

  foreach ( $request->subjects as $items)
  {

      $data = User::$request->only('name');
      $data['student_id'] = $userSave
      $subject= Subject::create($data);
   }
    DB::commit();
 } //sql transaction end
Dinesh
  • 159
  • 3
  • 15