t0berius
1 month ago
333
17
General

laravel observer not udpating value

Posted 1 month ago by t0berius

Updated my application yesterday to laravel8 now facing this problem:

public function updating(User $user){

    //check if EXP amount was updated
    if($user->isDirty('exp')){

        //increased
        if($user->exp > $user->getOriginal('exp')){
            $nextLevel = $user->currentLevel->nextLevel();

            while(!is_null($nextLevel) && $user->exp >= $nextLevel->experience_required) {
                $user->current_level = $nextLevel->id;

                $nextLevelID = $nextLevel->id + 1;
                $nextLevel = UserLevel::where('id', $nextLevelID)->first();
            }
        }

}

Users can earn EXP and gain access to new levels. In the old laravel7 version I've used a trait to make sure the increment() method will trigger the observer. As stated in the new laravel8 release the increment() function will trigger the model events too.

The event itself is triggered correctly, but for some reason it seems like the line

                $user->current_level = $nextLevel->id;

will not be written into the database. Any idea how to fix this? I'm a bit clueless, because the code itself is working fine, using a simple Log::info() shows the correct level is assigned too.

Please sign in or create an account to participate in this conversation.