In this tutorial you will learn about the How to Check User Online or Not in Laravel 7 and its application with practical example.
In this How to Check User Online or Not in Laravel 7 I’ll show you how to check User Online or Not in Laravel 7 using custom middleware. In this tutorial you will learn to check user is online or not in laravel. In this step by step guide we will be creating a custom middleware to check User Online or Not.
How to Check User Online or Not in Laravel 7
- Step 1: Install New Laravel App
- Step 2: Add Database Detail
- 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 New Laravel App
First of all we need to create a fresh laravel project, download and install Laravel using the below command
1 |
composer create-project --prefer-dist laravel/laravel blog |
Step 2: Add Database Details
Now, lets create a MySQL database and connect it with laravel application. After creating database we need to set database credential in application’s .env file.
1 2 3 4 5 6 |
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=here your database name here DB_USERNAME=here database username here DB_PASSWORD=here database password here |
Step 3: Generate Auth Scaffolding
In this step we will be generating laravel’s auth scaffolding using following command:
1 2 3 4 5 6 |
# 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
You need to add one column in the users table called last_seen. So, navigate database>migrations folder and open create_users_table file. Then update the last_seen column in this file as follow:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public function up() { Schema::create('users', function (Blueprint $table) { $table->bigIncrements('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(); }); } |
Now, run the migration to create database table using following artisan command:
1 |
php artisan migrate |
Step 5: Create a Middleware
In this step we will creating custom middleware using following command:
1 |
php artisan make:middleware ActivityByUser |
Next, navigate to app>Http>Middleware and open ActivityByUser.php middleware. Then update the following code into your middleware file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php namespace App\Http\Middleware; use App\User; use Closure; use Auth; use Cache; use Carbon\Carbon; class ActivityByUser { public function handle($request, Closure $next) { if (Auth::check()) { $expiresAt = Carbon::now()->addMinutes(1); // keep online for 1 min Cache::put('user-is-online-' . Auth::user()->id, true, $expiresAt); // last seen User::where('id', Auth::user()->id)->update(['last_seen' => (new \DateTime())->format("Y-m-d H:i:s")]); } return $next($request); } } |
Step 6: Register Middleware in Kernel
In this step, navigate app>Http and open Kernel.php. And register ActivityByUser.php middleware in the kernal.php file. You can see as follow:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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\ActivityByUser::class, ], 'api' => [ 'throttle:60,1', \Illuminate\Routing\Middleware\SubstituteBindings::class, ], ]; |
Step 7: Create Controller by Artisan
Now, lets create a controller named UserController using command given below –
1 |
php artisan make:controller UserController |
Next, navigate to app>Http>Controllers and open UserController.php file. Then update the following method into your UserController.php file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php namespace App\Http\Controllers; use App\User; use Carbon\Carbon; use Illuminate\Http\Request; use Cache; class UserController extends Controller { /** * Show user online status. */ public function userOnlineStatus() { $users = User::all(); foreach ($users as $user) { if (Cache::has('user-is-online-' . $user->id)) echo $user->name . " is online. Last seen: " . Carbon::parse($user->last_seen)->diffForHumans() . " <br>"; else echo $user->name . " is offline. Last seen: " . Carbon::parse($user->last_seen)->diffForHumans() . " <br>"; } } } |
Open routes>web.php and create a route:web.php
1 |
Route::get('/status', 'UserController@userOnlineStatus'); |
Step 8: Check Online Status in Blade File
1 2 3 4 5 |
@if(Cache::has('user-is-online-' . $user->id)) <span class="text-success">Online</span> @else <span class="text-secondary">Offline</span> @endif |
Navigate to resources>views and open home.blade.php. Then update the following code into home.blade.php.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
@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"> @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('user-is-online-' . $user->id)) <span class="text-success">Online</span> @else <span class="text-secondary">Offline</span> @endif </td> <td>{{ \Carbon\Carbon::parse($user->last_seen)->diffForHumans() }}</td> </tr> @endforeach </tbody> </table> </div> </div> </div> </div> </div> </div> @endsection |
Step 9: Run Development Server
Now we are ready to run our example so lets start the development server using following artisan command –
1 |
php artisan serve |