Search code examples
laraveleloquentaudit-traillaravel-auditing

Laravel Auditing - How To Get Specific Column Using Eloquent Model Method


I'm using Laravel Auditing Package to trace changes on my models. I want to get a specific column of the foreign key in it's primary table before recording the events (create, update, delete) in the audit table.

There is a way the package helps get all the attribute of the foreign key, it's called Audit Transformation but it generates an error for me when displaying the details in the table i want to know if there's any eloquent model method to get the specific column info i need instead of using getattribute() method which gets the entire row of the item_id.

Audit Transformation Method

public function transformAudit(array $data): array
{

    if (Arr::has($data, 'new_values.item_id')) {
        $data['old_values']['item_name'] = Item::find($this->getOriginal('item_id'));
        $data['new_values']['item_name'] = Item::find($this->getAttribute('item_id'));
    }

    return $data;
}

This is how it's stores in the database ephasis on the item_name.

{"item_id":"1","qty_received":"2","delivered_by":"John",
"received_by":"Abi","supplier":"Stores","date":"2019-11-26","item_name":{"item_id":1,"item_name":"Toner","colour":"Black","status":"Active",
"created_at":"2018-10-25 17:55:26","updated_at":"2018-10-25 17:55:26"}}

And this is the Item table schema Item Schema

So in my scenario i'd want to store the item_name as Toner not the entire row of the item_id Any suggestion will be welcomed, thanks in advance.


Solution

  • Add ->item_name->item_name after the function of Find.

     if (Arr::has($data, 'new_values.item_id')) {
        $data['old_values']['item_name'] = Item::find($this->getOriginal('item_id'))->item_name->item_name;
        $data['new_values']['item_name'] = Item::find($this->getAttribute('item_id'))->item_name->item_name;
    }