spatie / laravel-activitylog

Log activity inside your Laravel app
https://docs.spatie.be/laravel-activitylog
MIT License
5.3k stars 712 forks source link

Add trait to return a models last activity as a relation #1213

Closed chrisrhymes closed 1 year ago

chrisrhymes commented 1 year ago

This adds a new trait that can be added to models that already use the activity log. The trait allows the model to have the last activity as a relation of the model or models.

This trait is inspired by this article by Jonathan Reinink.

$newsItem = NewsItem::withLastActivity()->first();

$newsItem->lastActivity // Activity model

Or multiple models.

$newsItems = NewsItem::withLastActivity()->get();

$newsItems[0]->lastActivity // Activity model

You can also specify the event type to return, such as 'created' or 'updated'.

$newsItem = NewsItem::withLastActivity('updated')->first();
Gummibeer commented 1 year ago

There's a special Laravel has one of many relationship which doesn't need any subquery or scopes.

chrisrhymes commented 1 year ago

Thanks, I wasn't aware of the has one of many relationship. I updated the PR with this relationship but the tests are now failing. I think I'll just make this a trait in my own app.