spatie / activitylog

A very simple activity logger to monitor the users of your website or application
https://spatie.be/opensource/laravel
MIT License
582 stars 75 forks source link

Logging model events without a logged in user #9

Closed jmedlin closed 9 years ago

jmedlin commented 9 years ago

I would like to log the activity of events that happen on a model just like your example. Since the create, update, delete functions are being called by an API there is no logged in user. I'm getting this error when making my API call.

exception 'ErrorException' with message 'Argument 1 passed to BFCampaigns\SourceCode::Spatie\Activitylog\{closure}() must implement interface Spatie\Activitylog\logsActivityInterface, instance of BFCampaigns\SourceCode given' in /app/vendor/spatie/activitylog/src/Spatie/Activitylog/LogsActivity.php:10

Is there a way to assign events without a logged in user to some default system user account?

jmedlin commented 9 years ago

Here is my implementation inside of my model class

    public function getActivityDescriptionForEvent($eventName)
    {
        if ($eventName == 'created')
        {
            return 'Source Code (' . $this->source_code . '): "' . $this->entry_name . '" was created';
        }

        if ($eventName == 'updated')
        {
            return 'Source Code (' . $this->source_code . '): "' . $this->entry_name . '" was updated';
        }

        if ($eventName == 'deleted')
        {
            return 'Source Code (' . $this->source_code . '): "' . $this->entry_name . '" was deleted';
        }

        return '';
    }
kerwitz commented 9 years ago

Your model needs to implement the LogsActivityInterface interface as shown in the log model events section of the README. By default the code will fall back to an empty string if no user id can be obtained from the Auth provider.

I just made a pull request that enables you to customize this fallback value from the config. With this, you may default to either '' or 0 to indicate "anonymous" or you could create a user model for your system tasks and insert its id.

jmedlin commented 9 years ago

Worked perfectly, thank you.

kerwitz commented 9 years ago

No problem!