Search code examples
phplaravellaravel-nova

How can I add a callback function to Laravel Nova on storing a new resource?


In Nova's ResourceStoreController.php, I can see this code:

$model = DB::transaction(function () use ($request, $resource) {
    [$model, $callbacks] = $resource::fill(
        $request, $resource::newModel()
    );

    if ($request->viaRelationship()) {
        $request->findParentModelOrFail()
                ->{$request->viaRelationship}()
                ->save($model);
    } else {
        $model->save();
    }

    ActionEvent::forResourceCreate($request->user(), $model)->save();

    collect($callbacks)->each->__invoke();

    return $model;
});

Which certainly looks like I should be able to set a callback function to it looking at this line:

collect($callbacks)->each->__invoke();

But how can I set a callback for a particular resource in Laravel Nova?

Basically, I want to trigger an event or callback when I store a new resource, but only when the resource is created through nova.


Solution

  • For Nova <= 2.x:

    I was able to accomplish this with a hidden field as of Nova's latest version, then just using normal laravel observers to check for the field on update.

    Updated November 2020 for Nova ^3.0+:

    You can now create a Laravel Observer specific for your Nova usages and tell Nova to use it by adding this to your NovaServiceProvider:

    Nova::serving(function () {
        User::observe(UserObserver::class);
    });
    

    Docs here:

    https://nova.laravel.com/docs/3.0/resources/#resource-events