Table of Contents
Broadcast service provider
Setting up Redis connection
Create Event
Set api routing
Install front-end scaffolding
Redis
Install laravel-echo-server and subscribe to Redis Sub
Initialize laravel-echo-server
Start laravel-echo-server
Test broadcast
Install the pre-dependency of laravel-echo
Edit resource/js/bootstrap.js and add the following code
测试页面
基本构建
Home PHP Framework Laravel Let's talk about the broadcast mechanism of laravel7.0, there is always what you want!

Let's talk about the broadcast mechanism of laravel7.0, there is always what you want!

Jul 28, 2021 pm 03:57 PM
broadcast mechanism

laravel7.0 broadcast mechanism (Redis socket.io)

Broadcast service provider

Before broadcasting any event, you first need to registerApp\ Providers\BroadcastServiceProvider. In the newly installed Laravel application, you only need to uncomment the corresponding service provider in the providers array in the config/app.php configuration file. This provider allows you to register broadcast authorization routes and callbacks

Related column tutorial recommendations: "laravel tutorial"

Setting up Redis connection

Need to modify the broadcast driver in the .env file to redis:

BROADCAST_DRIVER=redis
Copy after login

Create Event

php artisan make:event OrderShipped
Copy after login

After executing the appeal command, an Events directory will appear in the app directory, and the broadcast event class OrderShipped.php will be generated in this directory. We need to make the following modifications to the automatically generated OrderShipped class

  • Add the implementation of ShouldBroadcast

  • Modify the broadcastOn method and use the public broadcast channel orderStatus

  • Customize the broadcast message name (Not required) [By default, Laravel will use the class name of the event to broadcast the event, but you can pass it in the event Define the broadcastAs method in to customize the broadcast name:】

  • Modify the constructor

The complete modification is as follows and can be directly replaced

<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class OrderShipped implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    //可添加任意成员变量
    public $id;
    //事件构造函数
    public function __construct($id)
    {
        $this->id = $id;
    }
    //自定义广播的消息名
    public function broadcastAs()
    {
        return &#39;anyName&#39;;
    }
    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new Channel(&#39;orderStatus&#39;);
    }
}
Copy after login

Set api routing

Route::get(&#39;/ship&#39;, function (Request $request) {
    $id = $request->input(&#39;id&#39;);
    broadcast(new OrderShipped($id)); // 触发事件
    return &#39;Order Shipped!&#39;;
});
Copy after login

Install front-end scaffolding

composer require laravel/uiphp artisan ui vue --auth
Copy after login

Redis

Because we use Redis broadcast , you need to install the Predis library:

composer require predis/predis
Copy after login

Redis broadcast uses the pub/sub function of Redis for broadcast; however, you need to combine it with the one that can accept Redis The Websocket server of the message is paired to broadcast the message to the Websocket channel

When Redis broadcasts an event, the event will be published to the specified channel, and the data passed is in a JSON format string, which contains the event name, load data data, and the user who generated the event socket ID

Install laravel-echo-server and subscribe to Redis Sub

If you use pusher, then directly Just use laravel. If you use Redis socket.io, you need to use the open source project laravel-echo-server. So now we are going to use laravel-echo-server

Global installation

npm install -g laravel-echo-server
Copy after login

Initialize laravel-echo-server

laravel-echo-server init

// 是否在开发模式下运行此服务器(y/n) 输入y
? Do you want to run this server in development mode? (y/N)// 设置服务器的端口 默认 6001 输入 6001就可以了 或者你想要的
? Which port would you like to serve from? (6001)// 想用的数据库  选择 redis
? Which database would you like to use to store presence channel members? (Use arrow keys)❯ redis
  sqlite

//   这里输入 你的laravel  项目的访问域名
? Enter the host of your Laravel authentication server. (http://localhost)// 选择 网络协议 http
? Will you be serving on http or https? (Use arrow keys)❯ http
  https

// 您想为HTTP API生成客户端ID/密钥吗 N
? Do you want to generate a client ID/Key for HTTP API? (y/N)// 要设置对API的跨域访问吗?(y/n)N
Configuration file saved. Run laravel-echo-server start to run server.

//您希望将此配置另存为什么? (laravel-echo-server.json)回车就行
? What do you want this config to be saved as? (laravel-echo-server.json)
Copy after login

Start laravel-echo-server

laravel-echo-server start
Copy after login
  • After successful startup, it will Output the following log
L A R A V E L  E C H O  S E R V E R

version 1.6.0

⚠ Starting server in DEV mode...

✔  Running at localhost on port 6001
✔  Channels are ready.
✔  Listening for http events...
✔  Listening for redis events...

Server ready!
Copy after login

Test broadcast

Execute on the browserhttp://yourhost/api/ship?id=16

Channel: laravel_database_orderStatus
Event: anyName
Copy after login
  • laravel-echo-server Connection successful!

Install the pre-dependency of laravel-echo

Since the front-end uses laravel-echo to listen to the broadcast, the underlying implementation we chose is socket.io. So first we need to add laravel-echo and socket.io dependencies

npm i --save socket.io-client
npm i --save laravel-echo
Copy after login
in
package.json

Edit resource/js/bootstrap.js and add the following code

import Echo from "laravel-echo";
window.io = require("socket.io-client");
window.Echo = new Echo({    
broadcaster: "socket.io",    
host: window.location.hostname + ":6001"
});
Copy after login

测试页面

resources/views/ 下建立页面 test.blade.php 内容为

<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="">
    <title>News Room</title>
    <link href="" rel="stylesheet">
</head>

<body>
    <div class="content">
        News Room
    </div>
    <script src=""></script>
    <script>
        Echo.channel("laravel_database_orderStatus") // 广播频道名称
    .listen(".anyName", e => {
        // 消息名称
        console.log(e); // 收到消息进行的操作,参数 e 为所携带的数据
    });
    </script>
</body>

</html>
Copy after login

js 代码的意思是收听 news 通道内的 News 事件对象,将接收到的事件在控制台打印出来。

基本构建

npm install && npm run watch
Copy after login

相关推荐:最新的五个Laravel视频教程

The above is the detailed content of Let's talk about the broadcast mechanism of laravel7.0, there is always what you want!. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I use Laravel's components to create reusable UI elements? How do I use Laravel's components to create reusable UI elements? Mar 17, 2025 pm 02:47 PM

The article discusses creating and customizing reusable UI elements in Laravel using components, offering best practices for organization and suggesting enhancing packages.

How do I create and use custom Blade directives in Laravel? How do I create and use custom Blade directives in Laravel? Mar 17, 2025 pm 02:50 PM

The article discusses creating and using custom Blade directives in Laravel to enhance templating. It covers defining directives, using them in templates, and managing them in large projects, highlighting benefits like improved code reusability and r

How can I create and use custom validation rules in Laravel? How can I create and use custom validation rules in Laravel? Mar 17, 2025 pm 02:38 PM

The article discusses creating and using custom validation rules in Laravel, offering steps to define and implement them. It highlights benefits like reusability and specificity, and provides methods to extend Laravel's validation system.

How do I use Laravel's Artisan console to automate common tasks? How do I use Laravel's Artisan console to automate common tasks? Mar 17, 2025 pm 02:39 PM

Laravel's Artisan console automates tasks like generating code, running migrations, and scheduling. Key commands include make:controller, migrate, and db:seed. Custom commands can be created for specific needs, enhancing workflow efficiency.Character

How can I use Laravel's routing features to create SEO-friendly URLs? How can I use Laravel's routing features to create SEO-friendly URLs? Mar 17, 2025 pm 02:43 PM

The article discusses using Laravel's routing to create SEO-friendly URLs, covering best practices, canonical URLs, and tools for SEO optimization.Word count: 159

How do I use database transactions in Laravel to ensure data consistency? How do I use database transactions in Laravel to ensure data consistency? Mar 17, 2025 pm 02:37 PM

The article discusses using database transactions in Laravel to maintain data consistency, detailing methods with DB facade and Eloquent models, best practices, exception handling, and tools for monitoring and debugging transactions.

Which is better, Django or Laravel? Which is better, Django or Laravel? Mar 28, 2025 am 10:41 AM

Both Django and Laravel are full-stack frameworks. Django is suitable for Python developers and complex business logic, while Laravel is suitable for PHP developers and elegant syntax. 1.Django is based on Python and follows the "battery-complete" philosophy, suitable for rapid development and high concurrency. 2.Laravel is based on PHP, emphasizing the developer experience, and is suitable for small to medium-sized projects.

How can I implement caching in Laravel to improve application performance? How can I implement caching in Laravel to improve application performance? Mar 17, 2025 pm 02:35 PM

The article discusses implementing caching in Laravel to boost performance, covering configuration, using the Cache facade, cache tags, and atomic operations. It also outlines best practices for cache configuration and suggests types of data to cache

See all articles