Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MySQL Transaction doesn't rollback with 0 affected rows – Laravel

I tried to make my first query return affected rows: 0 to see if the transaction fails but it continued executing the second query.

Should i break the transaction manually?

DB::transaction(function () {
  User::where('id', 1002)->update(['name' => 'x']); // id:1002 doesn't exist

  Post::where('user_id', 1)->update(['title' => 'New Title']);
});

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

There’s not a lot of context around your sample code, but a very basic approach would be something like this:

$user = User::findorFail(1002);
$user->update(['name' => 'x']);
if ($user->wasChanged('name')) {
    Post::where('user_id', 1)->update(['title' => 'New Title']);
}

So the first line will throw an exception if the model isn’t found. Then we do an update. You specifically said you were checking for 0 affected rows, so next we use the wasChanged() method. It "determines if any attributes were changed when the model was last saved within the current request cycle." If that’s the case, we proceed with the next update.

There are other changes that could be made involving, for example, route model binding if there was more of your code shown in the question, but hopefully this is a helpful start.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading