In this tutorial we will see how we can get online users with steps and examples in detail. You can follow along to get all logged users on a certain point in time easily. Let’s follow along and see how each step has been done. This method is applicable for all Laravel versions including 8 and 9.
To do that there are few basic things we need for that. The first of all in the ‘users table’ we have to include a new column “last_seen” and also add new middleware to check whether or not the user has logged-in. If the user was logged-in then the last_seen parameter will update automatically with that a new cache key will also be generated to check their login in future. So every time the user logs-in we will come to know that. Let’s get done with it.
#1 Create a New Laravel Project
Run this command in your terminal to create a new Laravel 10 project:
composer create-project --prefer-dist laravel/laravel^10
#2 Let’s Add A New Column That We Discussed
Next we have to add a new column in the user-table and create migration for “last_seen column. Use this command in the terminal:
php artisan make:migration add_new_column_last_seen
database/migrations/2022_10_22_042310_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()
{
}
}
Once done. Now we are going to add migrations by using this command:
php artisan migrate
In our app/Models/Users.php we need to add last_seen column on the user model
<?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',
];
}
#3 Next We Have to Generate Auth Scaffolding
By using this command we have to use laravel UI and generate auth scaffolding:
composer require laravel/ui --dev
Once we have installed the composer package we will use this command:
php artisan ui bootstrap --auth
Next we need to run Node Package Manager command:
npm i && npm run dev
#4 Now Let’s Create A Middleware
We are using this command to create our UserActivity to update last seen instance and also add the online status to that.
php artisan make:middleware UserActivity
Here we also have to update the middleware see here:
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); /* keep online for 2 min */
Cache::put('user-is-online-' . Auth::user()->id, true, $expiresAt);
/* last seen */
User::where('id', Auth::user()->id)->update(['last_seen' => now()]);
}
return $next($request);
}
}
Next we have also get this middleware registered to our kernel file here. Use this piece of code to add it to the kernel
app/Http/Kernel.php
<?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\RestrictIpAddressMiddleware::class,
\App\Http\Middleware\UserActivity::class,
],
'api' => [
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
...........
}
#5 Next we Have to Add Route
Now we are going to add a router so that we can show the online users function. Follow the code piece along here to understand each step thoroughly
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| We will create the route here you can do that as well.
| The RouteServiceProvider is used to load them in a group which
| contains the "web" middleware group.
|
*/
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::get('online-user', [UserController::class, 'index']);
#6 Now Let’s Create The Controller
We are going to add a UserController and use this code in the terminal for that:
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'));
}
}
#7 Now Let’s Add Blade File to Our Project
We will the resources/views for our blade file. See like this:
resources/views/users.blade.php
@extends('layouts.app')
@section('content')
<div class="container">
<h1>Laravel Get Online Users Details- Laramatic</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>
</div>
@endsection
Let’s run our server to check the changes we made and check login with user details.
php artisan serve
We will use local host to check the logged in or online users in our browser on this:
localhost:7000/logged-user
That’s how we can add add roles in laravel and get online-users details. For our all Laravel app checking the users online is very necessary features. If you have followed until now you are in line to master this tutorials. Let’s know in the comments for queries.