This is the most basic way to log activity:
activity()->log('Look mum, I logged something');
You can retrieve the activity using the Spatie\Activitylog\Models\Activity model.
$lastActivity = Activity::all()->last();
$lastActivity->description;
##Setting a subject
You can specify on which object the activity is performed by using performedOn():
activity()
->performedOn($someContentModel)
->log('edited');
$lastActivity = Activity::all()->last();
$lastActivity->subject;
The performedOn() method has a shorter alias: on()
##Setting a causer
You can set who or what caused the activity by using causedBy():
activity()
->causedBy($userModel)
->performedOn($someContentModel)
->log('edited');
$lastActivity = Activity::all()->last();
$lastActivity->causer;
The causedBy() method has a shorter alias: by()
If you're not using causedBy(), the package will automatically use the user who is logged in when log() is called, not when the logger is created. Calling tap() resolves the default causer before its callback runs. Use causedBy() to keep a specific causer if authentication changes before logging.
If you don't want to associate a model as causer of activity, you can use causedByAnonymous() (or the shorter alias: byAnonymous()).
##Setting custom properties
You can add arbitrary metadata to an activity by using withProperties(). This is separate from attribute_changes, which the package uses to store old/new model attribute values when logging model events.
activity()
->causedBy($userModel)
->performedOn($someContentModel)
->withProperties(['key' => 'value'])
->log('edited');
$lastActivity = Activity::all()->last();
$lastActivity->getProperty('key');
Activity::where('properties->key', 'value')->get();
##Setting custom created date
You can set a custom activity created_at date time by using createdAt()
activity()
->causedBy($userModel)
->performedOn($someContentModel)
->createdAt(now()->subDays(10))
->log('created');
##Setting custom event
You can set a custom activity event by using event()
activity()
->causedBy($userModel)
->performedOn($someContentModel)
->event('verified')
->log('The user has verified the content model.');
##Tap Activity before logged
You can use the tap() method to fill properties and add custom fields before the activity is saved.
The causer is available inside the callback, and changes to it are preserved when the activity is logged.
use Spatie\Activitylog\Contracts\Activity as ActivityContract;
activity()
->causedBy($userModel)
->performedOn($someContentModel)
->tap(function(ActivityContract $activity) {
$activity->my_custom_field = 'my special value';
})
->log('edited');
$lastActivity = Activity::all()->last();
$lastActivity->my_custom_field;