Skip to content
Advertisement

Laravel online status

I have made custom middleware to track user online status but it has an issue, I can see my own online status but I always see other users as offline while they are not.

Code

Middleware

class UserActivity
{
    /**
     * Handle an incoming request.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(Auth::check()){
            $expiresAt = Carbon::now()->addMinute(1);
            Cache::put('user-is-online-' . Auth::user()->id, true, $expiresAt);
        }
        return $next($request);
    }
}

Kernel.php

'web' => [
  //...
  AppHttpMiddlewareUserActivity::class,
],

User.php (model)

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

views

@if($user->isOnline())
  Online
@else
  Offline
@endif

Any idea why other users status is always not correct?

PS: I’m open to livewire solution if any 🙂

Advertisement

Answer

After digging in the chat we have resolved the issues;

Cache driver issue

Instead of using CACHE_DRIVER=array you have to use CACHE_DRIVER=file

Reason : array is used for testing purpose only and the state will not be persisted in cache between requests.

Livewire key issue

You have use <livewire:my-component key="UNIQUE_ID" /> or <div wire:key="UNIQUE_ID"></div> when the content is inside a foreach or if condition and updated by livewire.

Livewire keeps reference of them to update the DOM. Without, Livewire may update the wrong place.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement