


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.
Introduction
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.
Prerequisites
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 get free $100 DigitalOcean credits to 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:
Create a Controller
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.
Adding Event Streaming Methods
Once we have created our controller, we need to add the stream
method to it. This method will be used to send a stream of events.
Open the EventStreamController.php
file and add the following code:
<?php namespace App\Http\Controllers;use Carbon\Carbon;use App\Models\Trade;class StreamsController extends Controller{ /** * 事件流代码 * * @return \Illuminate\Http\Response */ public function stream(){ return response()->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:
- We use
response()->stream()
method to create an event stream. - Then we have an infinite loop that sends a stream of events every 50ms.
- If the client aborts the connection, we use
ob_flush()
andflush()
to send the event stream. - We use
sleep()
to wait 50ms before sending the next event. - We use
connection_aborted()
to break the loop if the client aborts the connection. - We use the
Carbon\Carbon
class to get the current date. - We use the
App\Models\Trade
model to get the latest transactions. This is for demonstration only, you can use any model you want. - Set the
Content-Type
header totext/event-stream
to tell the browser that the response is an event stream.
Enable output buffering
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 the php.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.
Add route
When requesting the /stream
route, we want to call the ``stream` method.
The route will be added to the routes/web.php
file as follows:
use App\Http\Controllers\StreamsController;Route::get('/stream', [StreamsController::class, 'stream']);
Using the event flow from the frontend
You can use Front-end frameworks such as Vue.js are 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]
Demo project
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 uses Materialize As a streaming database.
SSE vs WebSockets
Event streaming is great and easy to use, but it also has some advantages and disadvantages compared to other streaming protocols like WebSockets.
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
Conclusion
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: //www.php.cn/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!

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于单点登录的相关问题,单点登录是指在多个应用系统中,用户只需要登录一次就可以访问所有相互信任的应用系统,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于Laravel的生命周期相关问题,Laravel 的生命周期从public\index.php开始,从public\index.php结束,希望对大家有帮助。

在laravel中,guard是一个用于用户认证的插件;guard的作用就是处理认证判断每一个请求,从数据库中读取数据和用户输入的对比,调用是否登录过或者允许通过的,并且Guard能非常灵活的构建一套自己的认证体系。

laravel中asset()方法的用法:1、用于引入静态文件,语法为“src="{{asset(‘需要引入的文件路径’)}}"”;2、用于给当前请求的scheme前端资源生成一个url,语法为“$url = asset('前端资源')”。

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于使用中间件记录用户请求日志的相关问题,包括了创建中间件、注册中间件、记录用户访问等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于中间件的相关问题,包括了什么是中间件、自定义中间件等等,中间件为过滤进入应用的 HTTP 请求提供了一套便利的机制,下面一起来看一下,希望对大家有帮助。

laravel路由文件在“routes”目录里。Laravel中所有的路由文件定义在routes目录下,它里面的内容会自动被框架加载;该目录下默认有四个路由文件用于给不同的入口使用:web.php、api.php、console.php等。

在laravel中,scope用于处理模型中的数据,在模型中可以定义scope开头方法,这类方法可以通过模型直接调用,被称为查询作用域,语法为“public function scope首字母大写单词($query){...}”。


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

Atom editor mac version download
The most popular open source editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Zend Studio 13.0.1
Powerful PHP integrated development environment

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft