klevze/online-users

Display online users on a webpage

v0.1.2 2024-01-11 07:30 UTC

This package is auto-updated.

Last update: 2024-04-11 08:13:06 UTC


README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

"Online Users" is a Laravel package designed to effortlessly track and display the real-time count of users currently active on your web application. With seamless integration, this package provides a quick and reliable solution for monitoring and presenting the dynamic online user presence, enhancing the overall user experience on your Laravel-powered website.

Installation

You can install the package via composer:

composer require klevze/online-users

You can publish and run the migrations with:

php artisan vendor:publish --tag="online-users-migrations"
php artisan migrate

Integration with Laravel's Kernel Middleware

To enable the "Online Users" middleware in your Laravel application, follow these steps:

  1. Open the app/Http/Kernel.php file in your Laravel project.

  2. Locate the $middlewareGroups property, specifically within the web middleware group.

  3. Add the following line to the web middleware group:

    protected $middlewareGroups = [
        'web' => [
            // ... other middleware entries
            \Klevze\OnlineUsers\Middleware\TrackUserActivity::class,
            // ... other middleware entries
        ],
        // ... other middleware groups
    ];

Cleanup Inactive Users Console Command

The "CleanupInactiveUsers" console command provided by the "Online Users" package allows you to remove inactive users from the user_activities table. Follow the steps below to integrate and schedule the cleanup task.

  1. Open the app/Console/Kernel.php file in your Laravel project.

  2. Locate the schedule method and add the following entry to schedule the cleanup:inactive-users command every five minutes:

    protected function schedule(Schedule $schedule)
    {
        // ... other scheduled tasks
    
        $schedule->command('cleanup:inactive-users')->everyFiveMinutes();
    
        // ... other scheduled tasks
    }
  3. Save the changes to the Kernel.php file.

Now, the "CleanupInactiveUsers" console command will run every five minutes, cleaning up inactive users from the user_activities table.

Usage

Once package is installed, you can use the OnlineUsers class to get the number of active users. For example, the following code will get the number of active users:

$activeUsers = OnlineUsers::getActiveUsers();

Or you can use it directly in blade view:

<p>Currently browsing: {{ OnlineUsers::getActiveUsers() ?? 0 }}</p>

Demo

You can see a working demo at these sites:

License

The MIT License (MIT). Please see License File for more information.