Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rajitha-bandara/476a9c91257405fb1d76f67e2e4cf5a4 to your computer and use it in GitHub Desktop.
Save rajitha-bandara/476a9c91257405fb1d76f67e2e4cf5a4 to your computer and use it in GitHub Desktop.
Laravel Server Sent Events
use Symfony\Component\HttpFoundation\StreamedResponse;
$response = new StreamedResponse(function() use ($request, $data) {
while (true) {
echo 'data: ' . json_encode(['data' => $data]) . "\n\n";
ob_flush();
flush();
usleep(10000000);
}
});
$response->headers->set('Content-Type', 'text/event-stream');
$response->headers->set('X-Accel-Buffering', 'no');
$response->headers->set('Cach-Control', 'no-cache');
return $response;
In JS,
if (!!window.EventSource) {
var req_url = "{{route('ajax.booking_alerts')}}";
var source = new EventSource(req_url);
source.addEventListener("message", function(e) {
alerts_last_check = e.data.alerts_last_check;
console.log(e.data);
}, false);
source.addEventListener("open", function(e) {
console.log("Connection was opened.");
}, false);
source.addEventListener("error", function(e) {
console.log("Error - connection was lost.");
}, false);
} else {
alert("Your browser does not support Server-sent events! Please upgrade it!");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment