Skip to content

Instantly share code, notes, and snippets.

@lgalaz
Last active July 12, 2022 02:18
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save lgalaz/aec80abd40350161ff63 to your computer and use it in GitHub Desktop.
Save lgalaz/aec80abd40350161ff63 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>
@theavuthnhel
Copy link

Thank you very much.

@lgalaz
Copy link
Author

lgalaz commented Jan 14, 2020

Wow, this still works the same?
I think that code is from 2014, 3015.

Glad it's still relevant.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment