1
class ExampleUserService
{

    public function approve($user, $data)
    {

        $approvedUser = DB::transaction(function () use ($user, $data) {
            if ($data['approve_by_admin'] == 1) {
                $this->updateAdminStatus($user);
            }

            $user->update(['approved' => 1]); // This fires updated event
        });
    }

    public function updateAdminStatus($user, $data)
    {
        $user = DB::transaction(function () use ($user, $data) {

            //Some Logic

            $user->update(['status' => 5]); // This doesn't fire event
        });
    }
}

I have Scenario like above where same model gets updated in nested transactions but observer get only changes of last transaction, i want to get all updates in observer for same model.

1 Answer 1

1

Laravel waits until all transactions are finished before it triggers any observer events. This means if you update a model several times within nested transactions, only the last update’s change will trigger the observer.

To fix this -> Separate the transactions so that each update commits independently

    public function approve(User $user, array $data)
    {
        if ($data['approve_by_admin'] == 1) {
            $this->updateAdminStatus($user);
        }

        DB::transaction(function () use ($user) {
            $user->update(['approved' => 1]); 
        });
    }

And there are few issues/typos:

  1. Class name should be ServiceA not Service A

  2. Wrap the whole data in a single array

     $user->update(['approved' => 1]); # not $user->update(['approved'] => 1);
     $user->update(['status' => 5]);   # not $user->update(['status'] => 5);
    
  3. in updateAdminStatus($user){ your're passing one param $this->updateAdminStatus($user);, why this has two use ($user, $data) {

     public function updateAdminStatus(User $user)
     {
         DB::transaction(function () use ($user) {
             $user->update(['status' => 5]); 
         });
     }
    

FYI: Model Observer is kinda different what you have tried here. In short its like event-listener. Official doc

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.