Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if user online laravel

Tags:

php

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..

like image 393
Jadasdas Avatar asked Apr 28 '18 11:04

Jadasdas


People also ask

How can I check my laravel status?

You can go this way. Go to Auth/LoginController and add this line. For this to work you have to have a column named 'status' in users table. 1 is for active and 0/2 is for inactive user.


1 Answers

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/

like image 142
Mohammad Fanni Avatar answered Sep 22 '22 23:09

Mohammad Fanni