...

How to Implement User Last Seen Status in Laravel

Tracking user activity is a crucial part of modern web applications. Laravel provides a seamless way to monitor whether a user is online or to show their last activity time. In this guide, we’ll walk through implementing a "Last Seen" feature step-by-step using middleware, caching, and Blade views. Let’s make your Laravel app more interactive!

Introduction
Tracking user activity is a crucial part of modern web applications. Laravel provides a powerful way to track whether a user is online or show when they were last active. In this guide, we'll walk through how to build a 'Last Seen' feature step-by-step.

Step 1: Create Middleware
We start by creating a custom middleware that updates the user's online status and last seen timestamp.

// Middleware: LastSeen.php
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Carbon\Carbon;
use App\Models\User;

class LastSeen
{
    public function handle(Request $request, Closure $next)
    {
        if (Auth::check()) {
            $expireTime = Carbon::now()->addSeconds(30);
            Cache::put('user-is-online' . Auth::user()->id, true, $expireTime);
            User::where('id', Auth::user()->id)->update(['last_seen' => Carbon::now()]);
        }

        return $next($request);
    }
}

Step 2: Register Middleware
Next, register this middleware in your `app/Http/Kernel.php` file to ensure it runs on every web request.

// Register middleware in app/Http/Kernel.php
protected $middlewareGroups = [
    'web' => [
        // other middleware...
        \App\Http\Middleware\LastSeen::class,
    ],
];

In laravel 11 we can add accordingly

use  App\Http\Middleware\LastSeen;

->withMiddleware(function (Middleware $middleware) {
     $middleware->web(append:[LastSeen::class]);

})

Step 3: Update User Model
Add a `last_seen` column to the `users` table and update the User model to include a method to check online status.

// User Model: User.php
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;

class User extends Authenticatable
{
    use HasFactory;

    protected $fillable = [
        'name',
        'email',
        'phone',
        'password',
        'last_seen',
    ];

    public function UserOnline()
    {
        return Cache::has('user-is-online' . $this->id);
    }
}

Step 4: Create Migration
Run a migration to add the `last_seen` column to the `users` table.

// Migration: add_last_seen_to_users_table.php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddLastSeenToUsersTable extends Migration
{
    public function up(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->timestamp('last_seen')->nullable()->after('email');
        });
    }

    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('last_seen');
        });
    }
}

Step 5: Display Status in Blade View
Finally, show the user's online status and last activity time in your Blade view.

// Blade view: last_seen.blade.php
@if($value->UserOnline())
    <span class="badge badge-pill badge-success">Active Now</span>
@else
    <span class="badge badge-pill badge-danger">{{ Carbon\Carbon::parse($value->last_seen)->diffForHumans() }}</span>
@endif

Conclusion:
By following these steps, you can easily implement a user 'Last Seen' feature in Laravel. This allows you to show whether a user is currently online or the time they were last active. Customize the timing and cache settings to fit your application's needs.

Let me know if you want to extend this with real-time updates or add extra functionalities

William Anderson

I am a versatile Full-Stack Web Developer with a strong focus on Laravel, Livewire, Vue.js, and Tailwind CSS. With extensive experience in backend development, I specialize in building scalable, efficient, and high-performance web applications.