Search code examples
laravellumen

lumen observer is not working on the eloquent model


I am using lumen 5.5. I am trying to make the observer called on while updating/deleting the model. When i tried that with user model, observer is not calling. When i did that with the events everything works fine. It's not even shows any errors.

Here is my code:

AppServiceProvider.php

....
use App\Models\User;
use App\Observers\UserObserver;
...

public function boot() {
    User::observe(UserObserver::class);

}

App\Models\User.php

...
    public static function changeCustomerStatus(int $customerID): int{
        $customer = self::where([
                'id'        => $customerID,
                'user_type' => app('config')->get('user_type.CUSTOMER')
            ])
            ->first();

        if ($customer) {
            $customer->status = $customer->status == app('config')->get('status.ACTIVE') ? app('config')->get('status.DEACTIVE') : app('config')->get('status.ACTIVE');

            if ($customer->save()) {
                return $customer->status;
            }

            return 0;
        }   
        else 
            return 0;
    }
...

App\Observers\UserObserver.php

<?php

namespace App\Observers;

use App\Models\User;

class UserObserver {

    public function updated(User $user) {
        if ($user->status === app('config')->get('status.DEACTIVE')) {
            app('log')->info('updated');
        }
    }


public function saved(User $user) {
        if ($user->status === app('config')->get('status.DEACTIVE')) {
            app('log')->info('saved');
        }
    }


    public function deleted(User $user) {
        app('log')->info('deleted');
    }
}

I even did the composer dump-autoload. But no luck


Solution

  • Lumen doesn't have observe feature. You can use Events instead or make custom observer and call its functions from your code.

    Read docs here - Events