Laravel

Laravel 10 Check User Login, Online & Last Seen Status Example

Laravel

Laravel 10 Check User Login, Online & Last Seen Status Example

Tracking user login status, online presence, and last seen timestamp are essential features for many web applications. In Laravel 10, you can implement these functionalities using Eloquent models, middleware, and event listeners. In this example, we'll walk you through the process of checking user login status, online presence, and last seen timestamp in a Laravel application.

Step 1: Set Up the Database

First, create a new migration to add the necessary columns for tracking user status to the users table.

php artisan make:migration add_user_status_columns_to_users_table --table=users

In the generated migration file, add the following columns:

public function up()
{
    Schema::table('users', function (Blueprint $table) {
        $table->boolean('is_online')->default(false);
        $table->timestamp('last_seen_at')->nullable();
    });
}

Run the migration to update the database:

php artisan migrate

Step 2: Create a User Model

Next, we'll update the User model to include the newly added columns.

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $fillable = ['name', 'email', 'password', 'is_online', 'last_seen_at'];

    // Your existing User model code
}

Step 3: Implement User Status Middleware

Create a new middleware that sets the user's online status when they make a request to the application. We'll also update the user's last seen timestamp.

php artisan make:middleware UserStatusMiddleware

In the generated UserStatusMiddleware.php file, add the following logic:

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class UserStatusMiddleware
{
    public function handle($request, Closure $next)
    {
        if (Auth::check()) {
            $user = Auth::user();
            $user->is_online = true;
            $user->last_seen_at = now();
            $user->save();
        }

        return $next($request);
    }
}

Step 4: Register the Middleware

Register the UserStatusMiddleware in the app/Http/Kernel.php file by adding it to the $middleware array.

protected $middleware = [
    // Other middleware
    \App\Http\Middleware\UserStatusMiddleware::class,
];

Step 5: Create an Event Listener

Now, we'll create an event listener to update the user's online status when they log in and log out of the application.

php artisan make:listener UpdateUserStatusListener

In the generated UpdateUserStatusListener.php file, implement the logic to handle user login and logout events:

namespace App\Listeners;

use Illuminate\Auth\Events\Login;
use Illuminate\Auth\Events\Logout;
use Illuminate\Support\Facades\Auth;

class UpdateUserStatusListener
{
    public function handleLogin(Login $event)
    {
        $user = Auth::user();
        $user->is_online = true;
        $user->save();
    }

    public function handleLogout(Logout $event)
    {
        $user = Auth::user();
        $user->is_online = false;
        $user->save();
    }
}

Step 6: Bind the Listener

Bind the UpdateUserStatusListener to the events in the EventServiceProvider.php:

protected $listen = [
    // Other listeners
    \Illuminate\Auth\Events\Login::class => [
        \App\Listeners\UpdateUserStatusListener::class,
    ],
    \Illuminate\Auth\Events\Logout::class => [
        \App\Listeners\UpdateUserStatusListener::class,
    ],
];

Step 7: Display User Status in Views

In your application's views, you can display the user's online status and last seen timestamp:

@if(Auth::check())
    @if(Auth::user()->is_online)
        <p>User is online</p>
    @else
        <p>User was last seen at {{ Auth::user()->last_seen_at->diffForHumans() }}</p>
    @endif
@endif

Step 8: Test the Functionality

Now, you can test the user login status, online presence, and last seen timestamp functionality in your Laravel application. Log in and log out with different users to observe the changes in their online status and last seen timestamp.

Conclusion

Implementing user login status, online presence, and last seen timestamp in Laravel 10 is a valuable addition to your web application. By following this example and using middleware, event listeners, and the Eloquent model, you can easily track user activities and improve user experience.