Sivabalan
Sivabalan

Reputation: 1131

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

Upvotes: 2

Views: 2713

Answers (2)

Nee
Nee

Reputation: 31

Lumen does not have model observers the way Laravel does. I agree with using events or implementing your custom observers. If you choose to go with the latter, here is a post that might help. https://link.medium.com/ZHsJwJuvC5

Upvotes: 2

Malkhazi Dartsmelidze
Malkhazi Dartsmelidze

Reputation: 4992

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

Upvotes: 3

Related Questions