In this tutorial, we are going to learn how to get online users in our Laravel application. In here we are going to make our custom middleware.

Prerequisites

  • Laravel
  • To Continue with this tutorial, you should have installed Laravel 8 in your pc. If you are still not installed Laravel in your machine you can configure it from here.

    Setting up the Project

    First you need to create a new laravel project by running below command in your terminal

    1
    composer create-project laravel/laravel laravel-get-online-user

    Then navigate to your project directory by using below command in your terminal

    1
    cd laravel-get-online-user

    Set up Database details

    Now you need to configure your Database details in your .env file.

    1
    2
    3
    4
    5
    6
    DB_CONNECTION=mysql
    DB_HOST=127.0.0.1
    DB_PORT=3306
    DB_DATABASE=laravel_online_user
    DB_USERNAME=root
    DB_PASSWORD=

    Add new column to Users table

    We need to add last_seen column to default user migration file in our Laravel application.

    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
    <?php

    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;

    class CreateUsersTable extends Migration
    {
    public function up()
    {
    Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('email')->unique();
    $table->timestamp('last_seen')->nullable();
    $table->timestamp('email_verified_at')->nullable();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
    });
    }

    public function down()
    {
    Schema::dropIfExists('users');
    }
    }
    Then we need to migrate our migration files by running below command in your terminal:
    1
    php artisan migrate

    Also don’t forget to last_seen table value in app/Models/User.php file.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    <?php

    namespace App;

    use Illuminate\Contracts\Auth\MustVerifyEmail;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    use Illuminate\Notifications\Notifiable;

    class User extends Authenticatable
    {
    use Notifiable;

    protected $fillable = [
    'name', 'email', 'password', 'last_seen'
    ];

    protected $hidden = [
    'password', 'remember_token',
    ];

    protected $casts = [
    'email_verified_at' => 'datetime',
    ];
    }

    Generate Auth Scaffolding

    In here we use dafault auth scaffolding in Laravel. To install it run below command in your terminal:

    1
    composer require laravel/ui --dev
    After installing composer package, then run below command in your termianl:
    1
    php artisan ui bootstrap --auth

    To compile assets, run below command in your termianl:

    1
    npm i && npm run dev

    Create Middleware

    Now we need to create UserActivity middleware for update last seen time and add online status, to create middlware let's run bellow command:

    1
    php artisan make:middleware UserActivity

    After that place below code in UserActivity middleware:

    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
    <?php

    namespace App\Http\Middleware;

    use Closure;
    use Illuminate\Http\Request;
    use Auth;
    use Cache;
    use App\Models\User;

    class UserActivity
    {
    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);
    }
    }

    Then we need to register our newly created middleware in our kernal.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
    <?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,
    ],
    ];
    ...........
    }

    Create Controller

    Now we need to create UserController and add following code on that file:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    <?php

    namespace App\Http\Controllers;

    use Illuminate\Http\Request;
    use App\Models\User;

    class UserController extends Controller
    {
    public function index(Request $request)
    {
    $users = User::select("*")
    ->whereNotNull('last_seen')
    ->orderBy('last_seen', 'DESC')
    ->paginate(10);

    return view('users', compact('users'));
    }
    }

    Create View

    we need to create blade file called `/users.blade.php` in `resources/views` directory and paste this code in it:

    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
    @extends('layouts.app')

    @section('content')
    <div class="container">

    <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

    Create Route

    Change your web.php file according to this:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    <?php

    use Illuminate\Support\Facades\Route;

    use App\Http\Controllers\UserController;

    Auth::routes();

    Route::get('/', [UserController::class, 'index']);
    Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');

    Run the application

    To run your application run below command in your termial:

    1
    php artisan serve

    Then navigate to following URL:

    1
    http://127.0.0.1:8000/

    Conclusion

    In this tutorial, we learned how to get online users in Laravel. If you have any issue regarding this tutorial, mention your issue in comment section or reach me through my E-mail. You can obtainf the complete source code from this GitHub repository.