It looks like you want to ensure that the desactivatePrevious operation and the creation of a new model are both done within the same database transaction to maintain data integrity. To achieve this, you should move the DB::beginTransaction() call to before the desactivatePrevious method is called and ensure that both operations are within the try block. Here's how you can modify your code:
public function store(array $attributes)
{
DB::beginTransaction();
try {
if ($shouldBePaid) {
$this->desactivatePrevious($payments);
}
$new_model = Model::create($attributes);
DB::commit();
} catch (Exception $e) {
DB::rollBack();
// Handle the exception, e.g., log it or return an error response
throw $e;
}
}
private function desactivatePrevious(Collection $payments)
{
$payments->each(function (Payment $payment) {
$payment->status = 0;
$payment->save();
});
}
In this updated code, the transaction begins before any database operations. If an exception is thrown during either the desactivatePrevious method or the model creation, the transaction will be rolled back, and none of the changes will be applied to the database. This ensures that your database operations are atomic and that you won't end up with only part of the operations being applied.
Remember to pass the $payments collection and the $shouldBePaid variable to the store method if they are not already available within its scope. Also, make sure to handle the exception appropriately after rolling back the transaction, which might include logging the error or returning an error response to the user.