Determine User Online Status and Last Seen in Laravel

laravel detect (Determine) user online status example; In this tutorial, we will show you how to check and get the user online status and last seen in laravel application.

Making social media type app we need to show users status (online/offline) and last seen. So this tutorial will guide you step by step process to implement laravel determine users status and last seen.

This example is created in laravel 9, but you can use detecting user online status in laravel 5, laravel 6, laravel 7 or laravel 8 apps.

How to Check User Online Status in Laravel?

Follow the following steps to get user online/offline status and last seen in laravel apps;

  1. Download Laravel App
  2. Setup Database Configuration
  3. Modify Users Table
  4. Create Middleware for User Status
  5. Register Middleware in Kernel
  6. Make Routes
  7. Check Online Status in Controller
  8. Detect Online Status in Blade File
  9. Run Development Server

Step 1: Download Laravel App

First at all, open your terminal and run nthe following command for creating new laravel application.

composer create-project --prefer-dist laravel/laravel user-online-status

Go into the app:

cd user-online-status

Step 2 : Setup Database Configuration

This step explains how to make database connection by adding database name, username and password in .env config file of your project:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Enter_Your_Database_Name
DB_USERNAME=Enter_Your_Database_Username
DB_PASSWORD=Enter_Your_Database_Password

Step 3: Modify User Table

Next, navigate database/migration directory and open your users table migration then add the last_seen column inside it.

database\migrations\2014_10_12_000000_create_users_table.php

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->('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();
    });
}

After that run the migration command.

php artisan migrate

Step 4: Create Middleware for Detect User Status

Create a middleware named as UserLastActivity by typing this command:

php artisan make:middleware UserLastActivity

Now, navigate App/Http/Middlreware directory and open the app\Http\Middleware\UserLastActivity.php file and put the below code on it. Here we’re checking the user is active or not and last seen as well.

<?php

namespace App\Http\Middleware;

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

class UserLastActivity
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (Auth::check()) {
            $expireTime = Carbon::now()->addMinute(1); // keep online for 1 min
            Cache::put('is_online'.Auth::user()->id, true, $expireTime);

            //Last Seen
            User::where('id', Auth::user()->id)->update(['last_seen' => Carbon::now()]);
        }
        return $next($request);
    }
}

Step 5: Register Middleware in Kernel

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

protected $middlewareGroups = [
    'web' => [
        ....
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \App\Http\Middleware\UserLastActivity::class,
    ],

    'api' => [
        'throttle:60,1',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
];

Step 6 : Make Routes

In this step We have to add new route in route file Open web.php file add new route.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;

Route::get('users', [UserController::class, 'index']);

Step 7: Check Online Status in Controller

Now create controller for determining the user online status, So open your terminal and run the following command to create a new controller;

php artisan make:controller UserController

Now Open app\Http\Controllers\UserController.php file and put the below code inside it.

<?php

namespace App\Http\Controllers;

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

class UserController extends Controller
{
    public function index()
    {
        $users = User::all();
        return view('users', compact('users'));
    }
}

Step 8: Detect Online Status in Blade File

Now we will show the user last seen and active or inactive status in our blade file. So, navigate the resources/views directory and create a users.blade.php file. Now, open the resources\views\users.blade.php file and put the below code inside it;

@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">
                    <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('is_online' . $user->id))
                                            <span class="text-success">Online</span>
                                        @else
                                            <span class="text-secondary">Offline</span>
                                        @endif
                                    </td>
                                    <td>
                                        @if($user->last_seen != null)
                                            {{ \Carbon\Carbon::parse($user->last_seen)->diffForHumans() }}
                                        @else
                                            No data
                                        @endif
                                    </td>
                                </tr>
                            @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Step 9: Run Development Server

Now we are ready to run laravel check user online status and last seen example; you just need to add the below serve command in your terminal;

php artisan serve

After that the serve command share a url so you need copy the URL and past in browser. The url looks like below

http://localhost:8000/users

So, laravel detect (Determine) user online status example tutorial is over now, We have covered how to get user online status and last seen in laravel application. I hope you enjoy with this example;

Leave a Comment