Check If User Online Laravel

Check if user online laravel

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

Checking if the user is online in Laravel

It depends how you would define being online. Http is a stateless protocol.

You could however define being online as being active within the last five minutes. This way you can implement the function like this:

public function isOnline(): bool
{
return $this->last_activity->gt(Carbon\Carbon::now()->subMinutes(5));
}

also make sure to tag last_activity as a date:

protected $dates = ['last_activity'];

As your appliation grows I would think about another solution instead of loading all users from the database into memory.

How to Determine User Online Status/Offline status using Laravel?

You may use

Authentication Directives

The @auth and @guest directives may be used to quickly determine if the current user is authenticated or is a guest:

@auth
<a href="#">
<i class="fa fa-circle text-success"></i>
Online
</a>
@endauth

@guest
// The user is not authenticated...
@endguest

Edit (In case of fetching a list of users )

Step: 1 create a middleware
Create a middleware LastUserActivity using this command.

php artisan make:middleware LastUserActivity

Add some code check user online or not

\\App\Http\Middleware\LastUserActivity.php

<?php

namespace App\Http\Middleware;

use Closure;
use Auth;
use Cache;
use Carbon\Carbon;
class LastUserActivity
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if(Auth::check()) {
$expiresAt = Carbon::now()->addMinutes(1);
Cache::put('user-is-online-' . Auth::user()->id, true, $expiresAt);
}
return $next($request);
}
}

Step: 2 Add a class into Kernel

Add a class into Kernel file in middlewareGroups

protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,

\App\Http\Middleware\LastUserActivity::class,
],

'api' => [
'throttle:60,1',
'bindings',
],
];

Step: 3 Add a function into the User Model

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

Don't forget to add use Cache; in User Model At the top;

Step: 4 Check user Online or offline in Laravel application
Use the isOnline function in view.

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

Reference

Laravel online status

After digging in the chat we have resolved the issues;

Cache driver issue

Instead of using CACHE_DRIVER=array you have to use CACHE_DRIVER=file

Reason : array is used for testing purpose only and the state will not be persisted in cache between requests.

Livewire key issue

You have use <livewire:my-component key="UNIQUE_ID" /> or <div wire:key="UNIQUE_ID"></div> when the content is inside a foreach or if condition and updated by livewire.

Livewire keeps reference of them to update the DOM. Without, Livewire may update the wrong place.

Laravel : Web Api, how to find out if a user (application) is online?

Sounds like you may make use of Real-time connections such as Pusher

You would need presence channels to see who is online in JS, it works more client to client rather than the Laravel server knowing who is online.

You subscribe users to a channel and then you can see who else is on that channel.

https://laravel.com/docs/5.8/broadcasting#presence-channels

How to get online users(in real time)

Reading all the comments I've imagined two possible solutions:

Broadcast when a user logs in / out

This is the very simple solution. You can use laravel notifications that allows you to implement a specific broadcast logic:

  • During the login / logout phase create a UserLogged[In|Out] notification and broadcast it to a specific channel
  • Using Laravel Echo and a "few lines" of javascript, update your onlineUsers list (for example in VueJs you may want to update the Vuex store)

But this may require a more complex logic and you may have to write a lot of code to keep the online users list updated... I think it's better to move to solution #2...

Use presence channels

I think this is the best way, since it doesn't require nothing else that a good Laravel-echo configuration. For the example I'm using Pusher (since you asked for), but this solution can be implemented with all the Laravel broadcast drivers.

  • When a user logs in, simply subscribe him / her to a presence channel (here the Laravel documentation)
  • Using Laravel Echo, subscribe the user to that channel
var chatRoom = Echo.join('my.chat.room.id');
  • Once subscribed use themembers.count method to keep an updated list of the channel users.
  • Using a setTimeout() function you can have a realtime update of the users list.

Notes

I've never implemented this solutions in a production environment, but just wrote some code to see how it works. so I think that if other people have diffent point of view or have a better way to explain this process I will be happy to update my answer.



Related Topics



Leave a reply



Submit