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

Determine User Online Status in Laravel

Last modified on February 24, 2020 2 min read

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. I’m testing on Laravel 5.8. Let’s start:

Note: I’ve written a new article for Laravel 6+ users. Please take a look: How to Determine User Online Status & Last Seen in Laravel 6+.

Table of Contents

  1. Install Laravel and Basic Configurations
  2. Create a Middleware
  3. Add Middleware to Kernel
  4. Check Online Status in Controller
  5. Check Online Status in Balde File

Step 1 : 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.

After completing the basic configurations, run this command to generate Laravel primary authentication:

php artisan make:auth

Now migrate the migration:

php artisan migrate

Step 2 : 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 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 3 : Add Middleware to Kernel

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

Kernel.php
/**
 * The application's route middleware groups.
 *
 * @var array
 */
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',
        'bindings',
    ],
];

Step 4 : 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 Illuminate\Http\Request;
use DB;
use Cache;

class UserController extends Controller
{

    /**
     * Show user online status.
     *
     */
    public function userOnlineStatus()
    {
        $users = DB::table('users')->get();
    
        foreach ($users as $user) {
            if (Cache::has('user-is-online-' . $user->id))
                echo "User " . $user->name . " is online.
"; else echo "User " . $user->name . " is offline.
"; } } }

Open routes>web.php to create a route:

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

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

Step 5 : Check Online Status in Blade File

We can also easily show online status in 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>
                                </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>
                                    </tr>
                                @endforeach
                                </tbody>
                            </table>
                        </div>

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

Now login to your Laravel project to see the output. Here’s mine:

Determine User Online Status in Laravel
We have completed the project. 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.

12 Replies to “Determine User Online Status in Laravel”

  1. Hi Dear,

    I had contiune from step 2. (Because I have an app).

    It does not work on my Laravel 6.0.

    It shows every member is offline. But I’m online?

    What could be reason? and what is the working logic for this method? How it determines they are online/offline and put in the cache?

    Many thanks.

    1. Hi Yusril, you can keep the last seen time. In the handle() function of LastUserActivity.php you can add a line like this:

      User::where('id', Auth::user()->id)->update(['last_seen' => (new \DateTime())->format("Y-m-d H:i:s")]);

      I’ll also publish an article today on this topic. You can check later.

Leave a Reply

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