Home>Article>PHP Framework> An article explaining in detail how to quickly create a simple event flow in Laravel
This article brings you relevant knowledge about Laravel event flow. It mainly introduces what event flow is and how to create a simple event flow in Laravel. Interested friends should take a look. I hope everyone has to help.
Event streaming provides you with a way to send events to the client without reloading the page. This is useful for updating the user interface when live changes are made to the database.
Unlike traditional long polling using AJAX requests, in which multiple requests are sent to the server and a new connection is established each time, the event stream is sent to the client in real time in a single request .
In this article, I will show you how to create a simple event stream in Laravel.
Before you begin, you need to have Laravel installed on your machine.
I will be using the DigitalOcean Ubuntu Droplet in this demo. If you'd like, you can use my affiliate code to getfree $100 DigitalOcean creditsto launch your own server!
If you haven't already, you can follow the steps in this tutorial:
Or you can install it using this awesome script:
Let's start by creating a controller that handles the event stream.
Use the following command:
php artisan make:controller EventStreamController
This will create a new controller in the App\Http\Controllers directory.
Once we have created our controller, we need to add thestream
method to it. This method will be used to send a stream of events.
Open theEventStreamController.php
file and add the following code:
stream(function () { while (true) { echo "event: ping\n"; $curDate = date(DATE_ISO8601); echo 'data: {"time": "' . $curDate . '"}'; echo "\n\n"; $trades = Trade::latest()->get(); echo 'data: {"total_trades":' . $trades->count() . '}' . "\n\n"; $latestTrades = Trade::with('user', 'stock')->latest()->first(); if ($latestTrades) { echo 'data: {"latest_trade_user":"' . $latestTrades->user->name . '", "latest_trade_stock":"' . $latestTrades->stock->symbol . '", "latest_trade_volume":"' . $latestTrades->volume . '", "latest_trade_price":"' . $latestTrades->stock->price . '", "latest_trade_type":"' . $latestTrades->type . '"}' . "\n\n"; } ob_flush(); flush(); // 如果客户端中止连接,则中断循环(关闭页面) if (connection_aborted()) {break;} usleep(50000); // 50ms } }, 200, [ 'Cache-Control' => 'no-cache', 'Content-Type' => 'text/event-stream', ]); }}
The main things to note here are:
response()->stream()
method to create an event stream.ob_flush()
andflush()
to send the event stream.sleep()
to wait 50ms before sending the next event.connection_aborted()
to break the loop if the client aborts the connection.Carbon\Carbon
class to get the current date.App\Models\Trade
model to get the latest transactions. This is for demonstration only, you can use any model you want.Content-Type
header totext/event-stream
to tell the browser that the response is an event stream.In order for the above code to work properly, we need to enable output buffering in your PHP.ini file. This is done by adding the following line to thephp.ini
file:
output_buffering = On
It may be necessary to reload the PHP-FPM service after making this change. Or if you are using Apache, you can restart Apache.
When requesting the/stream
route, we want to call the ``stream` method.
The route will be added to theroutes/web.php
file as follows:
use App\Http\Controllers\StreamsController;Route::get('/stream', [StreamsController::class, 'stream']);
You can use Front-end frameworks such asVue.jsare used to handle event streams. But for this demo, I'm going to use pure Javascript.
The JavaScript snippet added to the blade template looks like this:
const eventSource = new EventSource('/stream');eventSource.onmessage = function(event) { const data = JSON.parse(event.data); if (data.time) { document.getElementById('time').innerHTML = data.time; } const newElement = document.createElement("li"); const eventList = document.getElementById("list"); newElement.textContent = "message: " + event.data; eventList.appendChild(newElement);}
To see this in action, you can try the following demo! [Related recommendations:laravel video tutorial]
If you want to understand how event streaming works, you can check out the demo project I created:
Laravel EventStream: Live Stock Trading Dashboard using Laravel and Materialize
Demo project not only shows the event stream but also has a simple front-end dashboard and usesMaterializeAs a streaming database.
Event streaming is great and easy to use, but it also has some advantages and disadvantages compared to other streaming protocols likeWebSockets.
For example, SSE is one-way, which means that once the connection is established, the server can only send data to the client, and the client cannot send data back to the server.
Unlike long polling, with WebSockets you have only one connection to the server, similar to SSE (Server Sent Events). The connection is duplex, which means you can send and receive data from the server.
If you want to learn more about the differences between SSE and WebSockets, check out this great video by Martin Chaov:Links
Related For more information on event streaming, check out this documentation from Mozilla here:
There, You'll find a more in-depth explanation of event streaming and how it works.
For more information about Materialize, watch this video here:Link
Hope you enjoyed this tutorial!
Original address:https://devdojo.com/bobbyiliev/how-to-cr...
Translated address:https: //m.sbmmt.com/link/09d45b92ec72b3c16ac64bbe4b97f539
The above is the detailed content of An article explaining in detail how to quickly create a simple event flow in Laravel. For more information, please follow other related articles on the PHP Chinese website!