DEV Community

Levskiy
Levskiy

Posted on

Simple Real-time in Laravel without WebSockets (Long Polling)

I created a lightweight package to handle Long Polling in Laravel effortlessly. It helps you keep your stack simple while getting real-time-like updates.

📦 laravel-long-polling

It allows you to hold the request until new data is available or a timeout occurs, significantly reducing server load compared to standard polling.

Installation

composer require levskiy0/laravel-long-polling
Enter fullscreen mode Exit fullscreen mode

How it works

Instead of spamming your server every second, you can simply wait for changes:

use Levskiy0\LongPolling\Facades\LongPolling;

LongPolling::broadcast('user-123', [
    'type' => 'notification',
    'message' => 'You have a new message',
    'data' => [
        'sender' => 'John Doe',
        'timestamp' => now()->toISOString(),
    ],
]);
Enter fullscreen mode Exit fullscreen mode
async function poll(offset = 0) {
  const tokenResponse = await fetch('/api/longpolling/token', {
    method: 'POST',
    body: JSON.stringify({ channel_id: 'user-123' }),
    headers: { 'Content-Type': 'application/json' }
  });
  const { token } = await tokenResponse.json();

  while (true) {
    const response = await fetch(
      `http://localhost:8085/getUpdates?token=${token}&offset=${offset}`
    );
    const { events } = await response.json();

    events.forEach(event => {
      // Update UI with each event
    });

    offset = events.length ? events[events.length - 1].id : offset;
  }
}

poll();
Enter fullscreen mode Exit fullscreen mode

Top comments (0)