Search code examples
laravelobserverslaravel-nova

Laravel Nova: Observing models and acting on Nova requests only


I have a bulk-operation endpoint in my api that allows for creating or adding many models in a single request. When these models are created, I dispatch a job to create an "audit" record that references all models that were created or updated.

I need the same functionality to trigger when someone creates or updates a record in Nova dashboard, but because of the above, I can't simply create a model observer or I would end up with duplicate "audit" records when making bulk api requests.

The best I can figure to do this is to create a model observer that is able to determine if the model being observed is being updated or created through nova specifically. How could I set up an observer on a model for the creating and updating events that would only run if the save or update came from a Nova request/resource?


Solution

  • According to Laravel Nova Documentation

    If you would like to attach an observer only during Nova related HTTP requests, you may register observers within Nova::serving event listener in your application's NovaServiceProvider. This listener will only be executed during Nova requests:

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
     public function boot()
     {
         parent::boot();
    
         Nova::serving(function () {
             User::observe(UserObserver::class);
         });
     }