How to Check User online or not in Laravel



This is post describes how to check user online or not in Laravel without storing any token in the database. we check user online or not based on recent activity using middleware.

Some developers use a token to store in the users' table when user login and delete token when user log out but what happens when the user, not log out but close the tab or maybe not on PC or system.

Here use a proper method use know user online or not we also seta time duration if the user does not do any activity duration set time. so let's start

Step:1 Create a new project

If you work on an existing project you can skip this process.

Create a new Laravel project using this command.

laravel new userOnline

Step:2 Setup database and migrate table

In the second step we setup database connection in the .env  file than migrate table using this command.

php artisan migrate

After that fill some dummy data in the user table to check user online or not in Laravel.

Step: 3 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: 4 Add a class into Kernel

Add a class into Kernal file in middlewareGroups

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

full code of $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: 5 Add a function into the User Model

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

Ok, We almost are done now time to check.

Step: 6 Check user Online or offline in Laravel application

Use the isOnline function in view.

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

 


About Author
  • user profile
    Brijpal Sharma

    brijpalsharma99@gmail.com, January 29th, 2018

    Hi, I am a web developer, I working on Laravel and CodeIgniter framework, I love to share knowledge and tutorials so I here...


0 Comment


You must be logged in to post a comment.


You may also be interested in...
jQuery plugin to validate the maximum length of the field and count characters.
Deploy Laravel Application To Shared Hosting The Easy and save Way
Laravel advance search filters with optional fields.
Laravel Migrations: Check if Table/Column Already Exists
Connect Multiple databases in the same Laravel project
SEO tool for Laravel Application
Paypal payment gateway integration in Laravel 5.7 step by step
How to Check User online or not in Laravel
How to keep filter data after the click to next button in Laravel pagination
Which is better for web development, Laravel or Flask?