Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save StanleyMasinde/9d114c7c864182b46af96ce3dabe33cf to your computer and use it in GitHub Desktop.
Save StanleyMasinde/9d114c7c864182b46af96ce3dabe33cf to your computer and use it in GitHub Desktop.
Server sent events with Laravel
Using nginx version: nginx/1.6.2 and Laravel 5
In the controller:
use Symfony\Component\HttpFoundation\StreamedResponse;
- - - - - - Some method - - - - - - - - -
$response = new StreamedResponse();
$response->headers->set('Content-Type', 'text/event-stream');
$response->headers->set('Cache-Control', 'no-cache');
$response->setCallback(
function() {
echo "retry: 100\n\n"; // no retry would default to 3 seconds.
echo "data: Hello There\n\n";
ob_flush();
flush();
});
$response->send();
In the page:
<script type="text/javascript">
var es = new EventSource("<?php echo action('Controller@Action'); ?>");
es.onmessage = function(e) {
console.log(e);
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment