


Server-Sent Events (SSE) is a great solution for enabling real-time notifications or updates in your application. Unlike WebSockets, SSE allows for one-way communication from the server to the client, making it lightweight and easy to implement. In this tutorial, we'll walk through how to set up SSE in a Laravel backend and consume the events in a Vue.js frontend.
Overview
We’ll be creating a simple real-time notification system using SSE. The server (Laravel) will push notifications to the client (Vue.js) whenever there are new notifications for the authenticated user. Here's a breakdown of what we'll cover:
- Backend (Laravel): Set up an SSE endpoint to stream notifications.
- Frontend (Vue.js): Set up an EventSource to listen for incoming notifications.
Step 1: Backend (Laravel)
1.1 Create an SSE Route in Laravel
In your routes/api.php, create an endpoint for the SSE stream. This will allow your Vue.js frontend to establish an SSE connection and listen for notifications.
use AppHttpControllersNotificationController;
Route::get('/notifications', [NotificationController::class, 'get']);
1.2 Controller Method for Streaming Notifications
Next, in the NotificationController, implement the logic to fetch unread notifications from the database and stream them to the client via SSE.
namespace App\Http\Controllers; use App\Models\Notification; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class NotificationController extends Controller { public function get(Request $request) { $headers = [ "Content-Type" => "text/event-stream", "Cache-Control" => "no-cache", "Connection" => "keep-alive", "X-Accel-Buffering" => "no", ]; return response()->stream(function () { while (true) { // Fetch the unread notifications for the authenticated user $notifications = Notification::where('clicked', 0) ->where('user_id', 2) // For now, hardcoding the user ID, you can replace it with Auth::id() for dynamic user handling ->get(); // If there are notifications, send them to the frontend if ($notifications->isNotEmpty()) { // Format notifications as JSON and send them via SSE echo "data: " . json_encode($notifications) . "\n\n"; } // Flush the output buffer ob_flush(); flush(); // Sleep for a few seconds before checking again sleep(5); } }, 200, $headers); } }
Explanation:
Streaming Response: The response()->stream() method is used to send an infinite stream of events.
Notifications: We are querying the Notification model for unread notifications (clicked = 0) for a specific user. The notifications are encoded as JSON and sent to the client.
Headers: The headers are set for SSE (Content-Type: text/event-stream).
Infinite Loop: The while (true) loop keeps the connection open and continuously sends new notifications every 5 seconds (adjustable by modifying sleep(5)).
Step 2: Frontend (Vue.js)
Now, let's set up the Vue.js frontend to listen for these notifications using the EventSource API.
2.1. Set Up Vue Component to Listen for SSE Events
Create a Vue component that will listen for the incoming events from the SSE stream.
<template> <div> <h3 id="Unread-Notifications">Unread Notifications</h3> <ul v-if="notifications.length"> <li v-for="notification in notifications" :key="notification.id"> {{ notification.message }} </li> </ul> <p v-else>No new notifications</p> </div> </template> <script> export default { data() { return { notifications: [], // Store notifications }; }, mounted() { // Initialize EventSource to listen to the /api/notifications endpoint const eventSource = new EventSource('/api/notifications'); // Handle incoming events from SSE eventSource.onmessage = (event) => { const data = JSON.parse(event.data); // Parse JSON data from the server this.notifications = data; // Update notifications list }; // Handle errors eventSource.onerror = (error) => { console.error("EventSource failed:", error); eventSource.close(); // Close the connection if there's an error }; }, beforeDestroy() { // Close the SSE connection when the component is destroyed if (this.eventSource) { this.eventSource.close(); } } }; </script>
Explanation:
- EventSource: We create an EventSource instance that listens to the /api/notifications endpoint. This establishes a persistent connection to the server. onmessage: This event listener processes incoming messages. The data is parsed from JSON and added to the notifications array. onerror: If an error occurs (e.g., if the SSE connection is lost), we log the error and close the connection.
- beforeDestroy: To prevent memory leaks, the SSE connection is closed when the component is destroyed.
Conclusion
In this tutorial, we’ve set up real-time notifications using Server-Sent Events (SSE) in a Laravel backend and a Vue.js frontend. SSE provides a simple and efficient way to push real-time updates to the client, making it an excellent choice for features like notifications. With minimal setup, you can enhance your application with live, real-time capabilities.
The above is the detailed content of Real-Time Notifications with Server-Sent Events (SSE) in Laravel and Vue.js. For more information, please follow other related articles on the PHP Chinese website!

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download
The most popular open source editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
