Search code examples
phplaraveleloquentobserver-pattern

Can Eloquent model observer access model data that are being affected by the event?


I am trying to create an observer for an Eloquent model to work as a logger for the changes on that model. I am not sure what parameters are passed to the observer's methods from the model. If the parameters don't include an instance of the updated model, is there another way around it without having to redefine the model class and override the needed methods?

class UserObserver{
    public static function saved($user){
        Activity::create([
            "activity-name" => "save",
            "user" => $user->id
        ]);
    }    

}

Solution

  • I found out that the model is actually passed, my mistake was not adding user property to the fillable array in the Activity model.

    usually, I get an exception when my application tries to update fields that are not included in the fillable array, but this time I didn't. anybody knows why?