Home > PHP Framework > Laravel > body text

Laravel implements the function of tracking whether the user is online

藏色散人
Release: 2020-01-30 20:57:28
forward
2665 people have browsed it

Laravel implements the function of tracking whether the user is online

Use a simple method in Laravel to track whether the user is online

Today, my task is to apply in Laravel On the program's user profile page, a green dot is added next to the username to indicate whether they are online.

My first thought was that we would need to start a node.js server and keep track of each user's active socket connections. Then using the currently logged in user socket, we can update the online status in real time!

The only problem is that this is a bit over the top for our current requirements and not completely necessary until we have features that require a second level of accuracy, like live chat.

A colleague pointed out that for current needs, the way MySpace handles "online" functionality may be sufficient. As far as we know, the way MySpace uses to show whether a user is online is based on their last activity on the site.

If their last activity was within X minutes, we'll show an "online" badge, if not, we won't. Simple!

Let’s add a field to the users table for the user’s last activity and update it on each page request. Then when we need to check if the user is online, we can compare that timestamp to the current timestamp and if it's within X minutes, then they are online!

While this can work fine, depending on the application you are building, it will add unnecessary writes to the database, which will slow down your application somewhat.

A good compromise is to store this information in the application cache. The benefit of caching is that this approach can be simplified because the cache can be set to expire.

Now that we have decided to implement this feature using caching, the next question is where should this code run so that it runs on every request? I have two ideas to achieve:

Create a BaseController and let all your Controllers inherit it

Create a middleware

After some Thinking about it, and realizing that I need to add a call to the parent constructor to all the constructors I've written, I chose to implement it in middleware.

We have a plan, let’s get into code!

First, we need to create a middleware. Enter the following command in the terminal:

php artisan make:middleware LogLastUserActivity
Copy after login

Next we open the following php file

app/Http/Middleware/LogLastUserActivity.php.
Copy after login

Add the following code in the handle method:

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

Next, we open the app/Http/Kernel.php file. If you are using Laravel 5.1 or earlier, you should place your code directly into the $middleware array. If your version is 5.2.*, you should place the code in $middlewareGroups of web.

Note that the code must be placed below the StartSession middleware, otherwise the Auth facade will not correctly log in the user. My update configuration settings are as follows:

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,
  \App\Http\Middleware\LogLastUserActivity::class,
  ],
 'api' => [
 'throttle:60,1',
 ],
 ];
Copy after login

The last step is to add a method to our user object to detect this value.

In app/User.php we add the following method:

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

Now in any page you can add the following method:

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

Important note--make sure to use use at the top of your file to introduce all facades!

I hope this helps you solve this problem!

For more technical articles related to the laravel framework, please visit the laravel tutorial column!

The above is the detailed content of Laravel implements the function of tracking whether the user is online. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!