How to add custom properties to Laravel Activities Log

Do you know how to add a custom properties in you laravel-activitylog?

Patrick Wan
2 min readMar 23, 2022

--

In Previous Article we talk about basic usage of activities log, but in some cases we might need to add custom properties in the log. So in this article I will show how to add custom properties in your log.

We can add custom properties to an activity by using withProperties()

activity()
->causedBy($userModel)
->performedOn($someContentModel)
->withProperties(['key' => 'value'])
->log('edited');
$lastActivity = Activity::all()->last(); //returns the last logged activity$lastActivity->getExtraProperty('key'); //returns 'value'$lastActivity->where('properties->key', 'value')->get(); // get all activity where the `key` custom property is 'value'

The example above is to add custom attribute in logs.

In my case, I would like to add the custom properties when the log was saving, so I no need to add one by one to the module.

Activity::saving(function (Activity $activity) {  $activity->properties = $activity->properties->put('agent', [    'ip' => request()->ip(),

--

--

Patrick Wan

My name’s Patrick. I’m a Software Developer, experience in Laravel, Vue Js, React Js, Livewire, Jquery, Codegniter, NPM, GIT. I have 5 years plus experience.