Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Benko's avatar
Level 6

Polymorphic and Eloquent

Okay, so basically I work on a kind of a dictionary, and I have tables words, tags and lists. Users can add any of these and manage (edit/delete) these items. All good. But I have decided to make a table contributions where all of that is recorded, i.e. if a word is added/edited/deleted, it is recorded, if a tag is added, it is recorded, etc.

Now, I have a website where I want to show that activity, so it would be a table with data like:

15 minutes ago Added a word "stalwart"
19 minutes ago Edited a word "palindrome"

The problem is I can get easily to the action, timestamp and the resource type being edited from the contributions table, however, I don't know how to pick a name based on the resource type and ID (like I have App\Word and 43, but can't get the word of ID 43). I could manually call the model class instance and pick the value, but that would call a plethora of queries, and I don't want that.

Is there a more convenient way to do this, ideally, something like:

Contribution::with('name')

Where the name would be the name of the word/tag/list, so that user would know what they affected?

Thanks.

0 likes
4 replies
realrandyallen's avatar

I use this package to handle this in one of the apps I work on, it was easy to setup and easy to use. It creates a table and polymorphic relationships, stores the old values, the new values, who did the change and when they did it

Might help you out

http://laravel-auditing.com/

2 likes
Mandrizzy's avatar

I don't fully understand you have a table contributions where you can get all the words, tag etc. that various users have added or deleted am i correct ?

Benko's avatar
Level 6

@MANDRIZZY - That's right, it's basically like a changelog where every single change that occurs in data gets recorded.

Mandrizzy's avatar
Level 5

Ok then just use a polymorphic relationship contribution may have many words tags etc. And words tags belongsto contributions then use the $with property to you contribution model to eager load all the words tags etc so you only execute what queries are needed to fetch everything and you can use nested eager loading to fetch the word creator dates etc from words

Please or to participate in this conversation.