Showing if a user is online in Laravel

James Mills > Blog > Showing if a user is online in Laravel

I’m working on a little project for work which will allow all our team to log in using our Google Mail accounts. I was able to get the auth set up quickly with Laravel Socialite and added a quick restriction to make sure that only people with an @clicksco.com email address was able to log in.

We are using the amazing Tailwind UI framework for the project and I’m using the Application UI >Lists > Wide Lists > Two-column with avatar list.

I wanted to use a little online indicator to show if the user was online or not

I decided to create a UserLastSeenAt Middleware and add it to my web routes file which would store the datetime the user was last seen in the cache.

First create the Middleware which can do using php artisan make:middleware UserLastSeenAt

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Cache;

class UserLastSeenAt
{
    public function handle($request, Closure $next)
    {
        Cache::put('user-last-seen:' . auth()->user()->id, now());

        return $next($request);
    }
}

Now register this new Middleware so you can use it in the route file

// App\Http\Kernel

use App\Http\Middleware\UserLastSeenAt;

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    ...
    'user.last.seen' => UserLastSeenAt::class,
];

Now you can use it in the web routes file like this

// web.php

Route::middleware('auth', 'user.last.seen')->group(function () {
    Route::get('/', 'HomeController@index')->name('home');
});

I then created a little helper function on my User model.

public function isOnline()
{
    $lastSeen = Cache::get('user-last-seen:' . $this->id, null);

    if (!is_null($lastSeen) && $lastSeen->diffInMinutes(now()) < 2) {
        return true;
    }

    return false;
}

And now in the blade view file I can just do this

<div class="flex-shrink-0">
    <span class="inline-block relative">
        <img class="h-12 w-12 rounded-full" src="{{ $user->avatar }}" />
        @if($user->isOnline())
            <span class="absolute top-0 right-0 block h-2.5 w-2.5 rounded-full text-white shadow-solid bg-green-400"></span>
        @endif
    </span>
</div>

One thought on “Showing if a user is online in Laravel

Leave a Reply

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