Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Rayray's avatar

How to check is user is Online through API

I have this in my Middleware

			  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' => now()]);
    }

    return $next($request);
			}

and this in my USER model

			public function isOnline(){

 return Cache::has('user_is_Online'.$this->id);

									}

how do i return all users wether online or not and add a value to identify online users from offline users using api

		 public function getusers($msg){
    $users = User::withBasic()->where('usertype_id' , 4)->orderBy('created_at' , 'DESC')->paginate(12);
     return response()->json([
        'res' => $users,
        'message'=>$msg,
        'status' => 200
    ], 200);
 }
0 likes
4 replies
Yamen's avatar

This is a wrong approach, you need to use websockets not a server side code. Laravel has an official library called Echo, you need to install it and use a websocker server like pusher or socket.it and then you can check online status or availability with Presence channel. Check this: https://laravel.com/docs/8.x/broadcasting#presence-channels

1 like
heyVanHeight's avatar

@Yamen May I know why we can't use the approach above and just use laravel echo? Instead if saying that it's a wrong approach, can you provide a reason, it's pros and cons. Thanks

Yamen's avatar

@heyVanHeight Sure no problem. The idea is there are some problems have a pattern to solve them, so if you searched the internet for something like how to check user is online through API you won't find a single solution mentioning session or cache or middleware because that's not how to do it. To check an online user activity there has to be some socket connection and whether this socket connection is up or not this is how to determine a user activity.

Snapey's avatar

suppose you do it this way, yet the usage of the application means that the user only navigates between pages every 2 minutes. So minute 1 they would be on-line, then in minute 2 they would be off-line then in minute 3 they might be considered that they are online again, and then offline 1 minute later

So we might expect the online status to be be incorrect 50% of the time.

To work out the status, get all users and then iterate over them, decorating the user model with the current status of the user (which can be determined by checking if there is a cache key for that user.

1 like

Please or to participate in this conversation.