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

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

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', 'UserController@userOnlineStatus');

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.