How to Check User Online Status & Last Seen in Laravel?


Share:
Published By: Admin, Published On: Jul 30, 2021, Category: Laravel 8 Laravel


Hey Artisan,

Today, I will justify you how can check user online status and last seen in laravel 8 application.So we can easily check the user is online or not. I will learn about how to recognize a user is online or not and store last seen data.

So,here User online or not and last seen store in laravel application. It is easy and simply to get last seen and online or offline display list of the user.

Here, I will give you full example for how can check user online status and last seen in laravel 8 so follow my all steps.

Step 1 : Install Laravel App

In this step, You can install laravel fresh app. So open terminal and put the bellow command.

composer create-project --prefer-dist laravel/laravel Status
Step 2 : Setup Database Configuration

After successfully install laravel app thenafter configure databse setup. We will open ".env" file and change the database name, username and password in the env file.

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 : Generate Auth

In this third step You can install auth in laravel. Open this link to install auth example.

Install Authentication Step 4 : Add Column in User Table

So after next step You can add column in user table So Let's Open terminal and run the bellow command:

php artisan make:migration add_last_seen_to_users_table --table=users	

Run successfully above command after add column into the user table.open migration file and put bellow code.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddLastSeenToUsersTable 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()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->timestamp('last_seen');
        });
    }
}

Put above code after run bellow command.

php artian migrate
Step 5 : Create Middleware

After successfully run migration next step we needed to create custom middleware as LastSeenStatusUserActivity using bellow command.

php artisan make:middleware LastSeenStatusUserActivity

Now open the middleware LastSeenStatusUserActivity.php file and paste bellow code in middleware file:

Path : app/http/middleware/LastSeenStatusUserActivity.php
<?php

namespace App\Http\Middleware;

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

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

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

Step 5 : Add Middleware in Kernel File

In this step We have to add middleware to kernel file.Open kernel.php file and add middleware.

Path : app/http/kernel.php
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\LastSeenStatusUserActivity::class,
    ],

    'api' => [
        'throttle:api',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
];
Step 6 : Add Route

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

Path : routes/web.php
<?php

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

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/status', [UserController::class,'show']);
Step 7 : Create Controller

In this step, we should need create new controller as UserController. So put bellow code.

Path : app/http/controller/UserController.php
<?php

namespace App\Http\Controllers;

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

class UserController extends Controller
{
    /**
     * Write Your Code..
     *
     * @return string
    */
    public function show()
    {
        $users = User::all();

        return view('status',compact('users'));
    }
}

Step 8 : Create View File

In this step, we should create blade file as status.blade.php and paste the bellow code into blade file.

Path : resources/views/status.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 bg-info text-white">
                        <h5>How to Check User Online Status & Last Seen in Laravel - MyWebTuts.com</h5>
                    </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>
                                    <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))
                                                <label class="badge badge-pill badge-success">Online</label>
                                            @else
                                                <label class="badge badge-pill badge-danger">Offline</label>
                                            @endif
                                        </td>
                                        <td>
                                            <label class="badge badge-info badge-pill">{{ \Carbon\Carbon::parse($user->last_seen)->diffForHumans() }}</label>
                                        </td>
                                    </tr>
                                @endforeach
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

Now we are ready to run our example so run bellow command for quick run:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/status
Output

It will help you...

Share: