laravelandme's avatar

Activity log for pivot table transactions

Hi,

I'm using Lumen (5.4.7) (Laravel Components 5.4.*) for my current project. I developed a custom trait to log the CRUD transactions of each model. Since the events do not fire for pivot table, I am unable to use a common method/trait to log the transactions of the pivot table.

I tried creating models for pivot table by extending 'Pivot' class, but I couldn't see the events getting fired and therefore the function mapped to the events were not executed. From laravel documentation, I understand that the regular events like save, update, etc., are not applicable for pivot tables.

Additional note: My pivot tables have other columns in addition to the foreign key fields.

After searching in so many forums, I have decided to ask here hoping to receive some help. My project expects to log the activities of all tables, so can anybody guide me on how to achieve this on pivot table.

Thank you, Malathy K.

0 likes
2 replies
laravelandme's avatar

@bobbybouwmann , I tried creating custom event and was able to confirm that the events are getting fired. But, I'm still unable to find a way to get the pivot tables entries to the event method.

Consider in my example, I have two parent tables named companies and themes with one pivot table named company_theme.

I wanted to log the transactions in my pivot table in my audit_trail table which has following fields: table_name, object_id (id field of the pivot table), field_names, old_value, new_value, event

Here is my controller function that triggers the custom event 'PivotAttach'.

public function newEvent() {
        $theme_ids = array(1, 2);
        $company = Company::find(1);
        $company->themes()->attach($theme_ids, [
            'created_by' => 1,
            'updated_by' => 1,
            'is_deleted' => 0]);
        event(new \App\Events\PivotAttach($company));
        return $company;
    }

I expect the following values to be logged in audit_trail table when the above controller function is executed.

| table_name | object_id | field_names | old_value | new_value | event | --- | --- | --- | --- | --- | --- | | company_theme | 1 | id,company_id,theme_id,created_by,updated_by,is_deleted | | 1,1,1,1,1,0 | created | company_theme | 2 | id,company_id,theme_id,created_by,updated_by,is_deleted | | 2,1,2,1,1,0 | created

Current function is only passing the parent table companies record to the event, but I want the pivot table records to be passed to the event, so that the event function can do necessary functions to log the records in the above mentioned expected format.

Can you please help me to find how to make this possible?

I'm also looking for options to record detach and updateExistingPivot functions.

Please or to participate in this conversation.