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>