Md Obydullah Follow I'm Md Obydullah. I build open-source projects and write about Laravel, Linux server, modern JavaScript and web development.

How to Determine User Online Status & Last Seen in Laravel 6+

Published on February 24, 2020 3 min read

in Laravel, we can easily determine the user is online or not. In this article, we will learn about how to detect a user is online or offline and store last seen data. I’m testing on Laravel 6.16.0. Let’s start:

Table of Contents

  1. Install Laravel and Basic Configurations
  2. Generate Auth Scaffolding
  3. Modify User Table
  4. Create a Middleware
  5. Add Middleware to Kernel
  6. Check Online Status in Controller
  7. Check Online Status in Blade File

Install Laravel and Basic Configurations

Each Laravel project needs this thing. That’s why I have written an article on this topic. Please see this part from here: Install Laravel and Basic Configurations.

Generate Auth Scaffolding

We’ve to enable auth scaffolding. Run these commands to enable auth scaffolding:

# install laravel ui
composer require laravel/ui --dev

# make auth
php artisan ui vue --auth

Done, we’ve enabled login/register options.

Modify User Table

We need to add one column in the users table called last_seen. Open users table migration file from database>migrations folder and in the up() functions add like this:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->timestamp('last_seen')->nullable();
        $table->rememberToken();
        $table->timestamps();
    });
}

Now migrate the migrations:

php artisan migrate

For an existing project, you can just add last_seen column to the users table.

Create a Middleware

Create a middleware named LastUserActivity by typing this command:

php artisan make:middleware LastUserActivity

Now open the middleware LastUserActivity.php from app>Http>Middleware and paste this code:

LastUserActivity.php
<?php

namespace App\Http\Middleware;

use App\User;
use Closure;
use Auth;
use Cache;
use Carbon\Carbon;

class LastUserActivity
{
    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' => (new \DateTime())->format("Y-m-d H:i:s")]);
        }

        return $next($request);
    }
}

In the middleware, we’re checking the user is active or not.

Add Middleware to Kernel

Go to app>Http and open Kernel.php. We have to add \App\Http\Middleware\LastUserActivity::class, line to $middlewareGroups like this:

Kernel.php
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::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',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
];

Check Online Status in Controller

We have done all the tasks. Now we can check the online status in the controller:

Create a controller named UserController:

php artisan make:controller UserController

Open the controller from app>Http>Controllers and paste this code:

UserController.php
<?php

namespace App\Http\Controllers;

use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Cache;

class UserController extends Controller
{

    /**
     * Show user online status.
     */
    public function userOnlineStatus()
    {
        $users = User::all();

        foreach ($users as $user) {
            if (Cache::has('user-is-online-' . $user->id))
                echo $user->name . " is online. Last seen: " . Carbon::parse($user->last_seen)->diffForHumans() . " <br>";
            else
                echo $user->name . " is offline. Last seen: " . Carbon::parse($user->last_seen)->diffForHumans() . " <br>";
        }
    }
}

Open routes>web.php and create a route:

web.php
Route::get('/status', '[email protected]');

Now run the project by typing php artisan serve and visit the route to see the output.

Check Online Status in Blade File

We can also easily show online status in the blade file. Here’s the syntax:

@if(Cache::has('user-is-online-' . $user->id))
    <span class="text-success">Online</span>
@else
    <span class="text-secondary">Offline</span>
@endif

Let’s see a full example. From resources>views, open home.blade.php and paste this code:

home.blade.php
@extends('layouts.app')

@section('content')
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">Users</div>

                    <div class="card-body">

                        @php $users = DB::table('users')->get(); @endphp

                        <div class="container">
                            <table class="table table-bordered">
                                <thead>
                                <tr>
                                    <th>Name</th>
                                    <th>Email</th>
                                    <th>Status</th>
                                    <th>Last Seen</th>
                                </tr>
                                </thead>
                                <tbody>
                                @foreach($users as $user)
                                    <tr>
                                        <td>{{$user->name}}</td>
                                        <td>{{$user->email}}</td>
                                        <td>
                                            @if(Cache::has('user-is-online-' . $user->id))
                                                <span class="text-success">Online</span>
                                            @else
                                                <span class="text-secondary">Offline</span>
                                            @endif
                                        </td>
                                        <td>{{ \Carbon\Carbon::parse($user->last_seen)->diffForHumans() }}</td>
                                    </tr>
                                @endforeach
                                </tbody>
                            </table>
                        </div>

                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

Now login to your Laravel project to see the output like this:

The tutorial is over. You can download this project from GitHub. Thank you. 🙂

You're welcome to suggest any article to write!

Md Obydullah Follow I'm Md Obydullah. I build open-source projects and write about Laravel, Linux server, modern JavaScript and web development.

Leave a Reply

Your email address will not be published. Required fields are marked *