Laravel 8 – How to Get Online Users in View?

In this tutorial, we will walk you through a step-by-step guide on how to display online users in Laravel. We will cover how to get all logged-in users and check if a user is online or not using Laravel. This guide is applicable to Laravel versions 6, 7, 8, 9, and 10.

The process involves adding a new “last_seen” column to the users table and creating a middleware to update the last_seen time and add a key for online status in the cache.

 

How to Show a list of Active Users in Laravel 8 Application?

Follow these quick steps to display list of active users on view page:

  • Step 1: Set up a new Laravel project
  • Step 2: Introduce a new column to the Users table
  • Step 3: Implement authentication scaffolding
  • Step 4: Develop a custom middleware
  • Step 5: Define the necessary routes
  • Step 6: Generate a new controller
  • Step 7: Establish Blade templates

 

 

Let’s dive into the details and get started.

Step 1: Set up a new Laravel project

First, we need to install a fresh Laravel 8 application using the command below. Open your terminal or command prompt and run the following command:

composer create-project --prefer-dist laravel/laravel blog

Step 2: Introduce a new column to the Users Table

In this step, we will create a new migration for adding the “last_seen” column:

php artisan make:migration add_new_column_last_seen

 

Update the migration file (database/migrations/2023_04_15_041308_add_new_column_last_seen.php) as shown below:

<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
class AddNewColumnLastSeen extends Migration
{
    public function up()
    {
        Schema::table('users', function(Blueprint $table){
            $table->timestamp('last_seen')->nullable();
        });
    } 
  
    public function down()
    {
          
    }
}

 

Run the migration command:

php artisan migrate

 

Now, add the last_seen column to the user model (app/Models/User.php):

<?php
  
namespace App\Models;
  
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
  
class User extends Authenticatable
{
    use HasFactory, Notifiable;

    protected $fillable = [
        'name', 'email', 'password', 'last_seen'
    ];
  
    protected $hidden = [
        'password', 'remember_token',
    ];
  
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

Step 3: Implement Authentication Scaffolding

To generate auth scaffolding, we will use Laravel UI. Run the following commands:

composer require laravel/ui --dev
php artisan ui bootstrap --auth
npm i && npm run dev

Step 4: Develop a Custom Middleware

Create a UserActivity middleware to update the last seen time and add online status. Run the following command:

php artisan make:middleware UserActivity

 

Update the middleware code (app/Http/Middleware/UserActivity.php) as shown below:

<?php
  
namespace App\Http\Middleware;
  
use Closure;
use Illuminate\Http\Request;
use Auth;
use Cache;
use App\Models\User;
  
class UserActivity
{
    public function handle(Request $request, Closure $next)
    {
        if (Auth::check()) {
            $expiresAt = now()->addMinutes(2); /* keep online for 2 min */
            Cache::put('user-is-online-' . Auth::user()->id, true, $expiresAt);
  
            /* last seen */
            User::where('id', Auth::user()->id)->update(['last_seen' => now()]);
        }
  
        return $next($request);
    }
}

 

Now, register this middleware in the kernel file (app/Http/Kernel.php):

<?php
  
namespace App\Http;
  
use Illuminate\Foundation\Http\Kernel as HttpKernel;
  
class Kernel extends HttpKernel
{
    // ...
    protected $middlewareGroups = [
        'web' => [
            // ...
            \App\Http\Middleware\UserActivity::class,
        ],
  
        'api' => [
            // ...
        ],
    ];
    // ...
}

Step 5: Define the Necessary Routes

In this step, we need to create routes for displaying online users functionality. Update the routes/web.php file as shown below:

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\UserController;
  
Route::get('/', function () {
    return view('welcome');
});
  
Auth::routes();
  
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
    
Route::get('online-user', [UserController::class, 'index']);

 

Step 6: Generate a New Controller

In this step, we need to create a UserController and add the following code to that file (app/Http/Controllers/UserController.php):

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\User;
  
class UserController extends Controller
{
    public function index(Request $request)
    {
        $users = User::select("*")
                        ->whereNotNull('last_seen')
                        ->orderBy('last_seen', 'DESC')
                        ->paginate(10);
          
        return view('users', compact('users'));
    }
}

Step 7: Establish Blade templates

Now, create the blade file for users (resources/views/users.blade.php):

@extends('layouts.app')
  
@section('content')
<div class="container">
    <h1>Laravel Display Online Users - FreakyJolly.com</h1>
  
    <table class="table table-bordered data-table">
        <thead>
            <tr>
                <th>No</th>
                <th>Name</th>
                <th>Email</th>
                <th>Last Seen</th>
                <th>Status</th>
            </tr>
        </thead>
        <tbody>
            @foreach($users as $user)
                <tr>
                    <td>{{ $user->id }}</td>
                    <td>{{ $user->name }}</td>
                    <td>{{ $user->email }}</td>
                    <td>
                        {{ Carbon\Carbon::parse($user->last_seen)->diffForHumans() }}
                    </td>
                    <td>
                        @if(Cache::has('user-is-online-' . $user->id))
                            <span class="text-success">Online</span>
                        @else
                            <span class="text-secondary">Offline</span>
                        @endif
                    </td>
                </tr>
            @endforeach
        </tbody>
</table>

</div>
@endsection

 

Now, we’re ready to run our example and log in with a user. Run the following command to quickly start the server:

php artisan serve

 

Now, you can open the following URL in your browser:

localhost:8000/online-user

This tutorial has provided you with a comprehensive guide to getting online users in Laravel. By following these steps, you can easily implement this functionality in your Laravel applications.

 

FAQs

 

  1. Can I use this method to track online users in Laravel 5? Yes, this method can also be applied to Laravel 5 with minor modifications.
  2. How do I customize the online time duration for users? You can customize the online time duration by changing the addMinutes(2) value in the UserActivity middleware.
  3. Can I use this method with other Laravel authentication packages? Yes, this method can be used with other Laravel authentication packages as long as the user model and authentication are properly configured.
  4. Is it possible to track the online status of guest users? This method focuses on tracking authenticated users. However, you can modify the middleware and implement additional logic to track guest users as well.
  5. Can I use this method to display the online status of users in real-time? While this method can display the online status of users, it is not real-time. You can use JavaScript, AJAX, or websockets to periodically update the user’s online status in real-time.

 

Conclusion

In this article, we have shown you how to get online users in Laravel by creating a middleware to track user activity, using the cache to store online users, and displaying the online users in a view. This is a useful feature for any web application that needs to display user activity.Good luck!

Leave a Comment

Your email address will not be published. Required fields are marked *