How to Get Online Users Laravel 8?
Oct 20, 2021 . Admin
Hey Artisan,
Today, I will justify to you how can check online users in laravel 8 application. So we can easily check the laravel check if a user is online or not. I will learn about how to recognize a user is online or not and store last seen data.
So, we will integrate the new column "last_seen" in the users table and create new middleware for a web that will check if the user login then it will update the last_seen time and add the key for online in the cache, so we can check user online or not using that. so just follow below steps.
Here, I will give you a full example of how can check laravel to get all logged-in users in laravel 8 so follow my all steps.
Step 1 : Install Laravel AppIn this step, You can install laravel fresh app. So open a terminal and put the bellow command.
composer create-project --prefer-dist laravel/laravel StatusStep 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_PasswordStep 3 : Create Auth using scaffold
Now, in this step, we will create auth scaffold command to create login, register and dashboard. so run following commands:
composer require laravel/ui
After, that you can run following command and check ui commands info.
php artisan ui --help
Next, You can use the following commands for creating auth:
Using Bootstrap:
php artisan ui bootstrap --auth
npm install
npm run devStep 4 : Add Column in User Table
So after the next step You can add a column in the user table So Let's Open the terminal and run the bellow command:
php artisan make:migration add_last_seen_to_users_table --table=users
Run successfully above command after adding column into the user table. open migration file and put below 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
Now,we will add this "last_seen" in User model.
Path: app/Models/User.php<?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 Middleware
After successfully run migration next step we needed to create custom middleware as UserActivity using bellow command.
php artisan make:middleware UserActivity
Now open the middleware UserActivity.php file and paste bellow code in middleware file:
Path : app/http/middleware/UserActivity.php<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use App\Models\User; use Auth; use Cache; 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()) { $expire = now()->addMinutes(2); /* keep online for 2 min */ Cache::put('user-is-online-' .Auth::user()->id,true,$expire); /* last seen */ User::where('id',Auth::user()->id)->update(['last_seen' => now()]); } return $next($request); } }Step 6 : 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.phpprotected $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\UserActivity::class, ], 'api' => [ 'throttle:api', \Illuminate\Routing\Middleware\SubstituteBindings::class, ], ];Step 7 : 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('online-user', [UserController::class, 'index']);Step 8 : 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 index() { $users = User::select('*') ->whereNotNull('last_seen') ->orderBy('last_seen','DESC') ->paginate(10); return view('users', compact('users')); } }Step 9 : Create View File
In this step, we should create blade file as users.blade.php and paste the bellow code into blade file.
Path : resources/views/users.blade.php@extends('layouts.app') @section('content') <div class="container"> <h4>Laravel 8 - How To Get Online Users- MyWebtuts.com</h4> <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="badge badge-success">Online</span> @else <span class="badge badge-danger">Offline</span> @endif </td> </tr> @endforeach </tbody> </table> </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/online-userOutput
It will help you...