Check User Online Offline Status on Laravel 10-Webourney
Today we will learn user online offline status check in laravel 10. In this article I will explain how to detect a user is online offline very easily. If you need a solution of how to check a user is online or offline than you are in the right post.
At the end of the article we will see the final output like bellow.
To complete this online offline status check process we have to follow several steps.
Let's see the steps at a glance:
1. Install Laravel Application
2. Database Create and Connect
3. Update User Migration
4. Run Migrate Command
5. Generate Auth Scaffolding
6. CheckStatus Middleware Create and Configure
7. Create Controller
8. Create Route
9. Create View
10. Test Application
Step 1. Install Laravel Application
To install a new laravel application we could use composer and laravel installer. Let's run the follwing command to create a new laravel 10 project. Keep in mind this method works any other laravel versions like laravel 9, laravel 8, laravel 7 etc.
//using composer
composer create-project laravel/laravel check-online-offline-status
//using laravel installer
laravel new check-online-offline-status
Step 2. Database Create and Connect
Here we will create a database and put its information into .env file to connect our application with the database.
DB_DATABASE=check-online-offline-status
DB_USERNAME=root
DB_PASSWORD=
Step 3. Update User Migration
Here we will add a new column check_online_offline _status and column type must be timestamp for cheaking user online offline status. By default it should be nullable() . Now open users migration file and update exactly same as shown bellow.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
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('check_online_offline_status')->nullable();
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('users');
}
};
Step 4. Run Migrate Command
Open your terminal and run the artisan migrate command.
php artisan migrate
Step 5. Generate Auth Scaffolding
Here we have to generate authhentication system for create user because for cheaking user online offline status we must have register users. With the help of breeze we will generate auth scaffolding. So run the bellow command to complete authentication process.
// Install Laravel Breeze using Composer
composer require laravel/breeze --dev
//Generate scaffolding
php artisan breeze:install
Step 6. CheckUserOnlineStatus Middleware Create and Configure
Now we will create a middleware and write the logic of online offline status for a user. Run the bellow code to create the middleware.
php artisan make:middleware CheckUserOnlineStatus
After successfully execute the command register and update the middleware with the bellow given code.
app\Http\Kernel.php
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\CheckUserOnlineStatus::class,
],
app\Http\middleware\ CheckUserOnlineStatus.php
<?php
namespace App\Http\Middleware;
use App\Models\User;
use Carbon\Carbon;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Symfony\Component\HttpFoundation\Response;
class CheckUserOnlineStatus
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
if (Auth::check()) {
$expiresAt = Carbon::now()->addMinutes(1); // keep online for 1 min
Cache::put('user_is_online_' . Auth::user()->id, true, $expiresAt);
User::where('id', Auth::user()->id)->update(['check_online_offline_status' => (new \DateTime())->format("Y-m-d H:i:s")]);
}
return $next($request);
}
}
Step 7. Create Controller
Now we need to create a controller to get all users and return a blade view file. Let's run the bellow command to create the controller.
php artisan make:controller UserListController
So update the UserListController controller like bellow:
app\Http\Controllers\ UserListController
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
class UserListController extends Controller
{
public function user_list()
{
$user_lists = User::all();
return view('user-list',compact('user_lists'));
}
}
Step 8. Create Route
In this step we will create a route. so upgrade the web.php file as shown bellow.
web.php
<?php
use App\Http\Controllers\ProfileController;
use App\Http\Controllers\UserListController;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('/dashboard', function () {
return view('dashboard');
})->middleware(['auth', 'verified'])->name('dashboard');
Route::middleware('auth')->group(function () {
Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');
});
Route::get('/user-list', [UserListController::class, 'user_list'])->name('user.list');
require __DIR__.'/auth.php';
Step 9. Create View
Finally we will create a view file to display both online and offline users list. So create a view file user-list.blade.php inside the resources\views directory and update with the following code.
resources\views\ user-list.blade.php
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel</title>
<!-- Fonts -->
<link rel="preconnect" href="https://fonts.bunny.net">
<link href="https://fonts.bunny.net/css?family=figtree:400,600&display=swap" rel="stylesheet" />
<!-- Styles -->
<style>
.antialiased{text-align: center; background:#e5e7eb}
</style>
</head>
<body class="antialiased">
<div class="relative sm:flex sm:justify-center sm:items-center min-h-screen bg-dots-darker bg-center bg-gray-100 dark:bg-dots-lighter dark:bg-gray-900 selection:bg-red-500 selection:text-white">
<div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
<div class="p-6 text-gray-900">
<h2>{{ __('Check user online offline status by WebJourney') }}</h2>
<hr>
<h4>{{ __('User List') }}</h4>
@foreach($user_lists as $user)
@if(Cache::has('user_is_online_' . $user->id))
<p> {{ __('online') }} - {{ $user->name}} </p>
@else
<p> {{ __('offline') }} - {{ $user->name }} </p>
@endif
@endforeach
</div>
</div>
</div>
</body>
</html>
Step 10. Test Application
Run the bellow command to browse laravel application.
php artisan serve
Now hit the url http://127.0.0.1:8000/register in the browser and register some users.
Now hit the url http://127.0.0.1:8000/user-list to see the online offline users list.
If you like what you are reading, please think about buying us a coffee as a token of appreciation.
We appreciate your support and are committed to providing you useful and informative content.
We are thankful for your ongoing support.
You May Read Bellow Articles:
Laravel 9 live search data in a table using ajax.
How to send SMS in laravel 9 using Twilio SMS API-Webjourney
Laravel 9 pdf invoice generate and download with barryvdh dompdf
How to create multi language website by laravel 9
Laravel 10 multiple form validation on the same page-WebJourney
Laravel 10 Breeze Authentication - WebJourney
Laravel 10 Ajax jQuery Crud with Pagination and Live Search
Laravel Naming Conventions Accepted by Laravel community
Laravel Shorter and More Readable Syntax - WebJourney