Check if user online laravel



PHP Snippet 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);
    }
}

PHP Snippet 2:

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

PHP Snippet 3:

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

PHP Snippet 4:

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

PHP Snippet 5:

        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,
],

PHP Snippet 6:

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();
    }
}

PHP Snippet 7:

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