-1

What's the best way to check a user's online status? I found two options, but I need advice to understand which one is better. The option I found: middleware and broadcast

Middleware simply hangs on all web routes and updates the status on each request:

if (Auth::check() && !Cache::has('user-is-online-' . Auth::user()->id)) {
    $expiresAt = Carbon::now()->addMinutes(5); // keep online for 5 min
    Cache::put('user-is-online-' . Auth::user()->id, true, $expiresAt);
    User::where('id', Auth::user()->id)->update(['last_seen' => now()]);
}

The middleware method is good, but it uses at least two queries to the database: checking authorization and getting an ID It seems to me that these two requests are too much for middleware.

What method would you recommend?

3
  • Why User::where('id' instead of Auth::user()? Commented Jun 22, 2023 at 23:20
  • Does it make a huge difference? Commented Jun 23, 2023 at 11:47
  • No, but it is more "laravel way", there are a lot of helpers and stuff already coded so you don't have to write it yourself, so less code Commented Jun 23, 2023 at 14:40

1 Answer 1

1

As I know both the middleware approach and the broadcast approach have their pros and cons.

But if in real-time updates and reducing database queries are critical for your application, the Broadcast Approach using WebSockets can be a good choice to take.

However in the other hand, If simplicity and performance are your top priorities, and you are willing to sacrifice an additional of database queries, then the Middleware Approach would be the recommended choice.

Sign up to request clarification or add additional context in comments.

2 Comments

Broadcasts are the last option, I think. Using them to simply determine online status is unwise. Now I've learned that Auth::check() requests and others don't make new requests to the database, but take existing data. This makes my job a lot easier, as I can check for the existence of the cache and therefore make fewer queries to the database!
yeah you are right ! broadcast approach can be really helpful in optimizing your work. I'm glad my suggestion was beneficial. If you need further assistance, feel free to reach out. Keep up the great work!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.