How to Determine User Online Status in Laravel
I will help you to determine user online status in Laravel with the example, Laravel pusher get online users, explain step by step. Here laravel admin page user online status determines if user online status green otherwise red.
Step 1 : Install Laravel and Basic Configurations
Read Also : Install Laravel and Basic Configurations
After completing the basic configurations, run this command :
php artisan make:auth
Now migration:
php artisan migrate
Step 2 : Create a middleware named UsersActivity by typing this command:
php artisan make:middleware UsersActivity
Now open the middleware app/Http/Middleware/UsersActivity.php
#app/Http/Middleware/UsersActivity.php
namespace App\Http\Middleware;
use Closure;
use Auth;
use Cache;
use Carbon\Carbon;
class UsersActivity
{
public function handle($request, Closure $next)
{
if (Auth::check()) {
$expiresAt = Carbon::now()->addMinutes(1);
Cache::put('user-is-online-' . Auth::user()->id, true, $expiresAt);
}
return $next($request);
}
}
Step 3 : Add Middleware to Kernel
#app/Http/Kernel.php
protected $middlewareGroups = [
...
'web' => [
\App\Http\Middleware\UsersActivity::class,
],
...
];
Step 4 : Create a controller
php artisan make:controller UserController
#app/Http/Controllers/usercontroller.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use Cache;
class UserController extends Controller {
public function index() {
$users = DB::table('users')->get();
return view('users',compact('users'));
}
}
Create route:
#route/web.php
Route::get('/users', 'UserController@index');
Step 5 : Blade File Display
#resources/views/users.blade.php
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row">
<div class="card">
<div class="card-header">Users</div>
@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>
</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>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
@endsection
Now run the project :
php artisan serve