Last active
July 12, 2022 02:18
-
-
Save lgalaz/aec80abd40350161ff63 to your computer and use it in GitHub Desktop.
Server sent events with Laravel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
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
Thank you very much.