jjmu15's avatar

Laravel Nova Actionable trait for non-nova events

Hi all,

I'm wondering if it is possible to log requests from a user (via an authenticated API request for example) using the actionable trait of Nova so I can see in the nova interface exactly who and when updated a resource?

I looked in the Nova documentation but only saw information about logging events for the Nova actions but I'd like to log generic action events too.

Thanks in advance for your help.

0 likes
9 replies
mibou520's avatar

Got the same question. I don't want to duplicate the work for non-Nova events. Do you have an answer?

gudorian's avatar

Had the same question as well and could not find anything regarding this in Nova documentation.

Digging around in Nova vendor files I found the Laravel\Nova\Actions\ActionEvent class which seems to be what Nova uses when saving entries to the action log.

You'll find some methods like forResourceCreate($user, $model) and forResourceUpdate($user, $model) which can be used for saving action log entries on model updates and saves.

There's some more methods to handle other cases but I haven't dug any further on those.

Do note tho, that you'll have to pass the Model that has been changed/pending creation to the ActionEvent class before saving it, otherwise it seems it can't extract what has changed so Original/Changes will be empty.

Below is an example snippet you can try to run ie. via php artisan tinker that will update the name on a User and log the changes to the action log.

Note that you'll have to create 2 users with id=1 and id=2 where user with id=2 is the one that will be logged as having changed user with id=1

auth()->loginUsingId(2);
$user = \App\User::find(1);
$user->name .= ' 2.0';
// Create ActionEvent instance before saving so Original/Changes is set correctly in action log
$actionEvent = \Laravel\Nova\Actions\ActionEvent::forResourceUpdate(auth()->user(), $user);
if ($user->save()) {
    // User model saved successfully so save entry in action log
    $actionEvent->save();
}

I'm not sure if this is the correct way but hopefully above should be a step in the right direction at least.

I've only tried and got it working using Nova v2.0.9 on Laravel 5.8.

2 likes
elemes's avatar

Thank you for this! Exactly what I needed. Confirmed working in Laravel 8.20.1 and Nova v3.18.0

mehrancodes's avatar

@gudorian Thanks for your fair explanation. As an update to Nova v3, we can now use this

Laravel\Nova\Nova::actionEvent()->forResourceUpdate($user, $model)->save();

1 like
TheAnswerIsAlwaysMaybe's avatar

Just wanted to say, in the latest Nova 4 version, this is default behaviour. So you just need the Actionable trait to log update / create actions.

Please or to participate in this conversation.