Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

cuecolla's avatar

Server Sent Events in Laravel for a Real-time Monitoring Dashboard

(Not a native english speaker, please bare with me.)

I'm trying to implement a real-time web dashboard using Laravel. I've never tried SSE nor websockets before but after researching about the two, I believe SSE is the most suitable for me since I only want to be able to read data from a database. I already started making the project and the real-time worked but only for one script at a time.

So in my web.php, there's one route (/sse) pointing to a controller which has fetchData() that returns a streamed response.

Route::get('/sse', [SSEController::class, 'fetchData'])->middleware(['auth'])->name('sse');
Route::get('/dashboard', [DashboardController::class,'index'])->middleware(['auth', 'verified'])->name('dashboard'); // inside here is a script that listens to sse endpoint
// use statements

class SSEController extends Controller
{
    public function fetchData()
    {
        $response = new StreamedResponse(function () {
            $this->setSSEHeaders();

            while (true) {
                $notifsData = $this->fetchNotifsFromDB();
                $notifAlert = RequestNotifs::select('created_at')->get();

                $this->sendSSEMessage('newRequest', $notifAlert);
                $this->sendSSEMessage('notifs', $notifsData);
                sleep(1);
            }
        });

        return $response;
    }

    private function sendSSEMessage($event, $data)
    {
        echo "event: $event\n";
        echo "data: $data\n\n";
        //Log::info("SSE: $data[0]");
        ob_flush();
        flush();
    }

    private function fetchNotifsFromDB()
    {
        $notifs = RequestNotifs::orderBy('created_at', 'desc')->get();
        return $notifs->toJson();
    }

    private function fetchOverallFromDB()
    {
        $overall = OverallMoods::all();
        return $overall->toJson();
    }

    private function setSSEHeaders()
    {
        header('Content-Type: text/event-stream');
        header('Cache-Control: no-cache');
        header('Connection: keep-alive');
    }
}

the other script that listens to the same sse endpoint

<main>
            <script src="{{ asset('js/newRequest.js') }}"></script>
</main>

the scripts work but there's a delay between them. if one script is working well, another stops working which is not the scenario i wanted considering that the other script is an alert notification that shows if there's a new data based on timestamp from the server-sent event. can someone help me on how to properly configure SSE in Laravel? or should i just use websockets?

0 likes
1 reply

Please or to participate in this conversation.