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']);
});
CodePudding user response:
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.