Laravel

Determine User Online Status in Laravel

Pinterest LinkedIn Tumblr

In this laravel tutorial, we will learn about how to check user online status and last seen.

If you need in your application user online status and last seen. At that time, you need to show users status (online/offline) and last seen. So this tutorial will guide you step by step from scratch to implement Laravel determine users status and last seen app.

Determine User Online Status in Laravel

Laravel Determine User Online Status in Laravel

First of all, you need to follow this step.


Step 1: Install laravel App
Step 2: Database Configuration in .env file
Step 3: Generate Auth Scaffolding
Step 4: Add Column in User Table
Step 5: Create a Middleware
Step 6: Register Middleware in Kernel
Step 7: Create Controller by Artisan
Step 8: Check Online Status in Blade File
Step 9: Run Development Server

Step 1: Install laravel 8 App

We need to run command to create Laravel 8 projects.

composer create-project --prefer-dist laravel/laravel laravel_loggedinUser
cd laravel_loggedinUser

Step 2 : Connecting App to Database

Next step, we will set the database credentials in the application. Let’s open your project .env file and set the database credentials here.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_loggedinuser
DB_USERNAME=root
DB_PASSWORD=root@123

Step 3: Generate Auth Scaffolding

In this step, Run the following commands to generate auth scaffolding:

install laravel ui
composer require laravel/ui --dev
auth scaffolding
php artisan ui vue --auth
finally run
npm i && npm run dev

Step 4: Add Column in User Table

here, we will create new migration for adding “last_seen” column:

php artisan make:migration add_new_column_last_seen

database/migrations/2021_07_18_123813_add_new_column_last_seen.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddNewColumnLastSeen extends Migration
{
/**
Run the migrations.
*
@return void
*/
public function up()
{
     Schema::table('users', function(Blueprint $table){
     $table->timestamp('last_seen')->nullable();
});
}
/**
Reverse the migrations.
*
@return void
*/
public function down()
{
}
}

now let’s run migration command:

php artisan migrate

now, just add last_seen column on user model as like bellow:

<?php
  
namespace App\Models;
  
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
  
class User extends Authenticatable
{
    use HasFactory, Notifiable;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'last_seen'
    ];
  
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
  
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

Step 5: Create a Middleware

here, we will create UserActivity for update last seen time and add online status, let’s run bellow command:

php artisan make:middleware UserActivity

now, update middleware code as bellow:

app/Http/Middleware/UserActivity.php

<?php
  
namespace App\Http\Middleware;
  
use Closure;
use Illuminate\Http\Request;
use Auth;
use Cache;
use App\Models\User;
  
class UserActivity
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        if (Auth::check()) {
            $expiresAt = now()->addMinutes(2); /* already given time here we already set 2 min. */
            Cache::put('user-is-online-' . Auth::user()->id, true, $expiresAt);
  
            /* user last seen */
            User::where('id', Auth::user()->id)->update(['last_seen' => now()]);
        }
  
        return $next($request);
    }
}

Step 6: Register Middleware in Kernel

Now register, this middleware to kernel file:

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
 protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \App\Http\Middleware\UserActivity::class,
        ],
  
        'api' => [
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];
}

Step 7: Create Controller by Artisan

php artisan make:controller UserController

in this step, we need to create UserController and add following code on that file:

app/Http/Controllers/UserController.php
<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\User;
  
class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $users = User::select("*")
                        ->whereNotNull('last_seen')
                        ->orderBy('last_seen', 'DESC')
                        ->paginate(10);
          
        return view('users', compact('users'));
    }
}

Step 8: Check Online Status in Blade File

here, we need to create blade files for users. so let’s create one by one files:

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

resources/views/users.blade.php

@extends('layouts.app')
  
@section('content')
<div class="container">
    <h1>User list - Active User</h1>
  
    <table class="table table-bordered data-table">
        <thead>
            <tr>
                <th>No</th>
                <th>Name</th>
                <th>Email</th>
                <th>Last Seen</th>
                <th>Status</th>
            </tr>
        </thead>
        <tbody>
            @foreach($users as $user)
                <tr>
                    <td>{{ $user->id }}</td>
                    <td>{{ $user->name }}</td>
                    <td>{{ $user->email }}</td>
                    <td>
                        {{ Carbon\Carbon::parse($user->last_seen)->diffForHumans() }}
                    </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>
    {{ $users->links() }}
</div>
@endsection

Step 9: Run Development Server

In this step, use the following php artisan serve command to start your server locally:

 php artisan serve

Check Active user

http://127.0.0.1:8000/online-user

Write A Comment