Laravel 10 – How to Get Online Users with IP Address in View

Laravel, an open-source PHP web framework, has gained widespread popularity among developers for its elegant syntax and modular architecture. The latest Laravel 10 version brings exciting features and improvements that enhance the development experience. In this article, we will explore how to get online users in view and fetch their IP addresses using Laravel.

Getting a list of online users in a web application can help the administrators understand user engagement and make informed decisions to improve the platform.

 

Let’s dive into the process of implementing this functionality in Laravel step by step.

 

Installing Laravel

First, we need to install Laravel. You can install it via Composer by running the following command:

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

Replace “OnlineUsersApp” with the desired name for your application.

 

Creating Middleware

Next, we’ll create a middleware to track the online users. Run the following command to generate a middleware file:

php artisan make:middleware TrackOnlineUsers

 

Open the newly created TrackOnlineUsers.php file and update the handle method as follows:

public function handle(Request $request, Closure $next)
{
    $user = auth()->user();
    if ($user) {
        $user->update([
            'is_online' => true,
            'last_seen' => now(),
        ]);
    }
    return $next($request);
}

 

Register this middleware in app/Http/Kernel.php:

protected $middlewareGroups = [
    'web' => [
        // ...
        \App\Http\Middleware\TrackOnlineUsers::class,
    ],
    // ...
];

Creating Model

Create a User model by running:

php artisan make:model User

 

Update the User.php file:

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    protected $fillable = [
        'name',
        'email',
        'password',
        'is_online',
        'last_seen',
    ];
    // ...
}

 

Creating Migration

Run the following command to create a migration file:

php artisan make:migration create_users_table

 

Update the create_users_table.php file with the following columns:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->boolean('is_online')->default(false);
        $table->timestamp('last_seen')->nullable();
        $table->rememberToken();
        $table->timestamps();
    });
}

 

Run the migration:

php artisan migrate

 

Creating Controller

Create a controller by running:

php artisan make:controller OnlineUsersController

 

Update the `OnlineUsersController.php` file with the following method:

public function index()
{
    $onlineUsers = User::where('is_online', true)->get();
    return view('online_users', compact('onlineUsers'));
}

 

Creating Routes

Now, update the routes/web.php file with the following route:

use App\Http\Controllers\OnlineUsersController;

Route::get('/online-users', [OnlineUsersController::class, 'index']);

 

Creating Views

Create a new file resources/views/online_users.blade.php and add the following code:

<!DOCTYPE html>
<html>
<head>
    <title>Online Users</title>
</head>
<body>
    <h1>Online Users</h1>
    <ul>
        @foreach($onlineUsers as $user)
            <li>{{ $user->name }} ({{ $user->ip_address }})</li>
        @endforeach
    </ul>
</body>
</html>

 

Displaying Online Users

Navigate to the /online-users URL in your browser to see the list of online users.

 

Accessing IP Addresses

To access the IP address of the users, update the handle method in the TrackOnlineUsers.php middleware:

public function handle(Request $request, Closure $next)
{
    $user = auth()->user();
    if ($user) {
        $user->update([
            'is_online' => true,
            'last_seen' => now(),
            'ip_address' => $request->ip(),
        ]);
    }
    return $next($request);
}

Update the User.php model and the create_users_table.php migration file with the ip_address column. Then, run the migration.

 

Conclusion

In this article, we have demonstrated how to get online users in view using Laravel . We have also shown how to access the IP address of the users. This functionality can be helpful for administrators to monitor user engagement and make informed decisions.

Leave a Comment

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