UsrLastly
This nifty little package makes it easy to store and retrieve a user's 'last seen' status., (*1)
It's a light implementation that's easy to extend., (*2)
It uses a middleware to check if a user is logged in, if so it will store the user's current visit., (*3)
Installation
First add the package to your composer file by runningthis command:, (*4)
composer require happydemon/usrlastly
This will install the latest version., (*5)
Next add the service provider in your app.php config:, (*6)
'providers' => [
...
'HappyDemon\UsrLastly\UsrLastlyServiceProvider',
]
Next publish the config file:, (*7)
php artisan vendor:publish
Now it's time to register LastSeenMiddleware as global middleware in app/Http/Kernel.php:, (*8)
protected $middleware = [
...
'HappyDemon\UsrLastly\Middleware\LastSeenMiddleware'
];
Lastly let's move on to your user model, open it and add the required trait:, (*9)
Above your class reference the trait, (*10)
use HappyDemon\UsrLastly\LastSeenTrait as LastSeen;
and in your user model add, (*11)
use LastSeen;
Storages
I've bundled 2 types of storage, this is where the 'last seen status' gets stored., (*12)
You can either store this status in your database or with Redis., (*13)
Database
To let this package do its work you'll first need to publish and run a database migration, (*14)
php artisan vendor:publish --provider="HappyDemon\UsrLastly\UsrLastlyServiceProvider" --tag="migrations"
php artisan migrate
That should have prepared your database and you should be ready., (*15)
Redis
This storage requires even less setup, all you have to do is open up config/userlastly.php and change the storage key to redis, (*16)
User provider
I'm sure not everybody is using Laravel's built-in Auth to handle user authentication so I've extracted this bit too,
at this moment though it's the only auth implemented., (*17)
This is something that's used by the package, not something other developers should worry about., (*18)
We can do this in 3 steps:, (*19)
- Create a class that implements
HappyDemon\UsrLastly\User with a getUser() method that returns a logged in user or false
- Binding that class to laravel's container
- Change
config/userlastly.php's user_provider key to name of that binding.
You can check the docs for the worked out example., (*20)
Retrieving 'last seen' status
Load your user like you would normally and call lastSeen(), as an example I'll just grab the first user in the database:, (*21)
$user = User::find(1);
dd($user->lastSeen());
That method should return an object with 2 properties:, (*22)
-
date which is a
Carbon date object
-
request, an array which holds information on where the user was