Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel User Last Seen At Laravel Package

lvlup-dev/laravel-user-last-seen-at

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require lvlup-dev/laravel-user-last-seen-at
    php artisan migrate
    

    The package auto-registers a migration to add last_seen_at to your users table.

  2. First Use Case: Add the middleware to your web routes in bootstrap/app.php:

    $middleware->web(append: [
        \LvlupDev\UserLastSeenAt\Http\Middleware\UserLastSeen::class,
    ]);
    

    Now, every authenticated request will update the last_seen_at timestamp for the user.

  3. Verify: Check a user’s record in the database or via Tinker:

    $user = \App\Models\User::first();
    echo $user->last_seen_at; // Should reflect the last request time
    

Implementation Patterns

Core Workflow

  1. Middleware Integration:

    • Append the middleware to route groups where you want to track activity (e.g., web, api).
    • Example for API routes:
      $middleware->api(append: [
          \LvlupDev\UserLastSeenAt\Http\Middleware\UserLastSeen::class,
      ]);
      
  2. Conditional Updates:

    • The middleware skips updates for unauthenticated users by default. Override this behavior by publishing the config:
      php artisan vendor:publish --provider="LvlupDev\UserLastSeenAt\ServiceProvider"
      
      Then configure update_guests in config/user-last-seen-at.php.
  3. Manual Updates:

    • Trigger updates programmatically (e.g., after login or specific actions):
      use LvlupDev\UserLastSeenAt\Facades\UserLastSeenAt;
      
      UserLastSeenAt::update(); // Updates for the current user
      UserLastSeenAt::update($user); // Updates for a specific user
      
  4. Query Scopes:

    • Use the provided scopes to filter users by activity:
      // Users seen in the last 5 minutes
      $activeUsers = \App\Models\User::seenIn('5 minutes')->get();
      
      // Users never seen
      $inactiveUsers = \App\Models\User::neverSeen()->get();
      
  5. Customizing the Column:

    • Change the column name by publishing the config and setting column_name.

Integration Tips

  • APIs: Combine with rate-limiting middleware to track active API users.
  • Admin Panels: Use the last_seen_at field to highlight recently active users in dashboards.
  • Notifications: Trigger "last seen" notifications via Laravel’s scheduler or event listeners:
    // Example: Notify admins of inactive users daily
    $this->app->booted(function () {
        \App\Models\User::whereNull('last_seen_at')
            ->orWhere('last_seen_at', '<=', now()->subDays(7))
            ->chunk(100, function ($users) {
                // Send notifications
            });
    });
    

Gotchas and Tips

Pitfalls

  1. Middleware Placement:

    • Issue: If placed after authentication middleware, the user might not be loaded yet.
    • Fix: Ensure the middleware runs before any logic that relies on auth()->user().
    • Example: In bootstrap/app.php, place it early in the web group:
      $middleware->web(append: [
          \App\Http\Middleware\EncryptCookies::class,
          \LvlupDev\UserLastSeenAt\Http\Middleware\UserLastSeen::class, // Early!
          // ...
      ]);
      
  2. Database Transactions:

    • Issue: The last_seen_at update runs in a separate query, which may cause transaction conflicts if not handled carefully.
    • Fix: Disable transactions temporarily if needed, or use DB::transaction() to group updates:
      DB::transaction(function () {
          // Your logic here
          UserLastSeenAt::update(); // Safe within transaction
      });
      
  3. Guest Updates:

    • Issue: Enabling update_guests may bloat your database with timestamps for anonymous activity.
    • Tip: Use this sparingly (e.g., for public forums) and consider adding a guest_id column to track sessions.
  4. Time Zone Handling:

    • Issue: last_seen_at timestamps use the server’s time zone by default.
    • Fix: Configure your app’s time zone in .env (APP_TIMEZONE=UTC) or use Carbon to normalize:
      $user->last_seen_at->setTimezone('America/New_York');
      

Debugging

  1. Middleware Not Triggering:

    • Verify the middleware is appended to the correct route group.
    • Check for errors in storage/logs/laravel.log or enable debug mode (APP_DEBUG=true).
  2. Column Missing:

    • Run php artisan migrate:fresh if the migration wasn’t applied.
    • Manually add the column if needed:
      Schema::table('users', function (Blueprint $table) {
          $table->timestamp('last_seen_at')->nullable()->after('updated_at');
      });
      
  3. Performance:

    • Issue: High traffic may slow down updates due to frequent writes.
    • Optimization: Use a queue to defer updates:
      UserLastSeenAt::queueUpdate(); // Uses Laravel queues
      
      Configure the queue in config/user-last-seen-at.php.

Extension Points

  1. Custom Logic:

    • Extend the middleware by binding your own logic to the updatingLastSeen event:
      // In a service provider
      event(new \LvlupDev\UserLastSeenAt\Events\UpdatingLastSeen($user));
      
  2. Model Observers:

    • Listen for retrieved events to log activity:
      class UserObserver {
          public function retrieved(Model $user) {
              if (auth()->check() && $user->id === auth()->id()) {
                  UserLastSeenAt::update();
              }
          }
      }
      
  3. Testing:

    • Mock the middleware in tests:
      $this->actingAs($user)
          ->withHeaders(['X-Test-Header' => 'value'])
          ->get('/dashboard');
      $this->assertDatabaseHas('users', [
          'id' => $user->id,
          'last_seen_at' => now(),
      ]);
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity