Skip to content

Commit

Permalink
Merge pull request #4 from cjmellor/user-last-activity
Browse files Browse the repository at this point in the history
Add new method to get users' last activity time
  • Loading branch information
cjmellor committed Sep 20, 2023
2 parents dfd37b6 + 8636714 commit dc146f5
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,20 @@ Then in your view, you can add a form to submit a `DELETE` request to the above
</form>
```

## Retrieve the Users' Last Activity

Get the users' last activity by using the `getUserLastActivity` method:

```php
BrowserSessions::getUserLastActivity();
```

You can also view the date in a human-readable format:

```php
BrowserSessions::getUserLastActivity(human: true);
```

## Credits

- [Chris Mellor](https://github.com/cjmellor)
Expand Down
13 changes: 13 additions & 0 deletions src/BrowserSessions.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ public function sessions(): Collection
'browser' => $agent->browser(),
'desktop' => $agent->isDesktop(),
'mobile' => $agent->isMobile(),
'tablet' => $agent->isTablet(),
'platform' => $agent->platform(),
],
'ip_address' => $session->ip_address,
Expand Down Expand Up @@ -74,4 +75,16 @@ protected function deleteOtherSessionRecords(): void
->where(column: 'id', operator: '!=', value: request()->session()->getId())
->delete();
}

public function getUserLastActivity(bool $human = false): Carbon|string
{
$lastActivity = DB::connection(config(key: 'session.connection'))->table(table: config(key: 'session.table', default: 'sessions'))
->where(column: 'user_id', operator: '=', value: Auth::user()->getAuthIdentifier())
->latest(column: 'last_activity')
->first();

return $human
? Carbon::createFromTimestamp($lastActivity->last_activity)->diffForHumans()
: Carbon::createFromTimestamp($lastActivity->last_activity);
}
}

0 comments on commit dc146f5

Please sign in to comment.