How to add custom properties to Laravel Activities Log

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

Patrick Wan

--

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(),   ]);});

So in our log will have the extra attribute below

{"agent": {"ip": "127.0.0.1"}, "attributes": {"name": "super-admin", "status": 1, "guard_name": "web"}}

If you would like to know more about Programming, please feel free to subscribe my channel. ^^

Read More Laravel Stories:

--

--

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.