'Check if user online laravel

I have column last_activity, where write date last activity user with middleware.
How I can check online user and when he logout?

Middleware:

class LastActivityUser
{
/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
  public function handle($request, Closure $next)
  {
    if (\Auth::check() && (\Auth::user()->last_activity < new \DateTime('-5 minutes'))) {
        $user = \Auth::user();
        $user->last_activity = new \DateTime;
        $user->timestamps = false;
        $user->save();
    }
    return $next($request);
  }
}

Code in User model:

public function online() {
    return ($this->last_activity > new \DateTime('-5 minutes') && $user->check()) ? true : false;
}

$user->check => Auth::check() - not working. I don't need use Auth::check(), I need show online user on other users.. But Auth::check() check if user stay in account only for current auth user..



Solution 1:[1]

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Factory as Auth;

class LastActivityUser
 {
     /**
     * The authentication factory instance.
     *
     * @var \Illuminate\Contracts\Auth\Factory
     */
     protected $auth;

     /**
     * Create a new middleware instance.
     *
     * @param  \Illuminate\Contracts\Auth\Factory  $auth
     * @return void
     */
     public function __construct(Auth $auth)
     {
         $this->auth = $auth;
     }
     /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
         if ($this->auth->check() && $this->auth->user()->last_activity < Carbon::now()->subMinutes(5)->format('Y-m-d H:i:s')) {
             $user = $this->auth->user();
             $user->last_activity = new \DateTime;
             $user->timestamps = false;
             $user->save();
        }
        return $next($request);
    }
}

Solution 2:[2]

you could use middleware to check online users

if(Auth::check()) {
    $expiresAt = Carbon::now()->addMinutes(5);
    Cache::put('user-is-online-' . Auth::user()->id, true, $expiresAt);
}

and check users:

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

in view:

@if($user->isOnline())
    user is online!!
@endif

maybe this document will help you : https://erikbelusic.com/tracking-if-a-user-is-online-in-laravel/

Solution 3:[3]

you can use below package in order to get a list of online users or determine if a user is online or not.

https://github.com/shetabit/visitor

Solution 4:[4]

  1. Create a middleware ActivityByUser 2)In the ActivityByUser Middleware

    class ActivityByUser { public function handle($request, Closure $next) { if (Auth::check()) { $expiresAt = Carbon::now()->addMinutes(1); // keep online for 1 min Cache::put('user-is-online-' . Auth::user()->id, true, $expiresAt); // last seen User::where('id', Auth::user()->id)->update(['last_seen' => (new \DateTime())->format("Y-m-d H:i:s")]); } return $next($request); } }

3)In the Kernel.php.

        protected $middlewareGroups = [
'web' => [
    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    \Illuminate\Session\Middleware\StartSession::class,
    // \Illuminate\Session\Middleware\AuthenticateSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    \App\Http\Middleware\VerifyCsrfToken::class,
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
    \App\Http\Middleware\ActivityByUser::class,
],
'api' => [
    'throttle:60,1',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],

4)Create a controller:

public function userOnlineStatus()
{
    $users = User::all();
    foreach ($users as $user) {
        if (Cache::has('user-is-online-' . $user->id))
            echo $user->name . " is online. Last seen: " . Carbon::parse($user->last_seen)->diffForHumans();
        else
            echo $user->name . " is offline. Last seen: " . Carbon::parse($user->last_seen)->diffForHumans();
    }
}

5)Check Online Status in Blade File

@if(Cache::has('user-is-online-' . $user->id))
<span class="text-success">Online</span>
@else
<span class="text-secondary">Offline</span>
@endif

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Praveen Tamil
Solution 2 Mohammad Fanni
Solution 3 Mahdi
Solution 4 Said ben hmed