Home PHP Framework Laravel Use Laravel Echo in 16 simple steps

Use Laravel Echo in 16 simple steps

Mar 27, 2020 am 11:41 AM
laravel

Use Laravel Echo in 16 simple steps

Let me start with a few words in English and talk about the role of Laravel Echo:

One of my favorite projects in the Laravel ecosystem is Echo. Echo enables real- time web applications through the use of WebSockets and hooks directly into Laravel's event broadcasting features. This means developers can use a familiar PHP API to send real-time data. A very common use-case for this type of functionality would be a notification or chat system.

Translation「Short」

Excerpted from: https://www.imarc.com/blog/realtime-notifications-with-laravel-echo-server-docker-and-traefik

The official documentation recommends using Pusher or laravel-echo-server (a WebSocket server implemented using NodeJS Socket.IO).

Recommendation: laravel tutorial

In China, individuals still do not recommend using Pusher, as the access speed is affected, and it is still a commercial product.

Today, use the simplest "16" steps to go through the code to integrate laradock and laravel-echo-server to use Laravel Echo.

Build the basic environment

// 1. new project
laravel new echolearning
// 2. 使用 laradock
git clone https://github.com/Laradock/laradock.git
// 3. 创建 .env
cp env-example .env
// 4. 创建 container
docker-compose up -d php-worker laravel-echo-server nginx redis
Copy after login

Use Laravel Echo in 16 simple steps

// 5. 进入 workspace 容器
docker-compose exec --user=laradock workspace bash
// 6. 安装插件
// 6.1 推荐使用 laravel-china 维护的 composer 国内镜像
composer config -g repo.packagist composer https://packagist.laravel-china.org
// 6.2 并行下载插件
composer global require "hirak/prestissimo"
// 6.3 配置 yarn 国内镜像
yarn config set registry 'https://registry.npm.taobao.org'
// 注:以上可以在 laradock 中配置
// 6.4 执行安装
composer install
yarn install
// 7. 创建 .env 和 key
cp .env.example .env
php artisan key:generate
Copy after login

Okay, let’s start typing in the browser: http://localhost, and the website will run Get up

Use Laravel Echo in 16 simple steps

Using Laravel Echo Server

Because laradock integrates "Laravel Echo Server", it is very convenient for us to use it Laravel Echo.

// 8. 配置广播驱动和 redis 服务器
BROADCAST_DRIVER=redis
REDIS_HOST=redis
// 9. 安装 predis
composer require predis/predis
Copy after login

After preparing the backend configuration, we started to install the front-end plug-in. After all, Laravel Echo is a front-end tool.

// 10. 安装 socket.io-client laravel-echo
yarn add socket.io-client laravel-echo
Copy after login

Instantiate Echo in resources/assets/js/bootstrap.js:

// 11. 实例化 Echo
import Echo from 'laravel-echo'
window.io = require('socket.io-client')
window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: window.location.hostname + ':6001'
});
// Laravel 官方推荐使用 pusher
// window.Pusher = require('pusher-js');
// window.Echo = new Echo({
//     broadcaster: 'pusher',
//     key: process.env.MIX_PUSHER_APP_KEY,
//     cluster: process.env.MIX_PUSHER_APP_CLUSTER,
//     encrypted: true
// });
Copy after login

Next we can use the Echo instance to listen to broadcasts or notifications sent by the backend.

First we use the given ExampleComponent to modify it, create an Echo listener, wait for the arrival of data, and then display it on the page. The code is simple:

<template>
    <div>
        <div class="row justify-content-center">
            <div>
                <div class="card card-default">
                    <div>Example Component</div>
                    <div>
                        <ul>
                            <li v-for="name in names" :key="name">{{ name }}</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
    export default {
        data () {
            return {
                names: []
            }
        },
        mounted() {
            let that = this
            // 12. 创建 Echo 监听
            Echo.channel(&#39;rss&#39;)
                .listen(&#39;RssCreatedEvent&#39;, (e) => {
                    that.names.push(e.name)
                });
        }
    }
</script>
Copy after login

We add an rss created event RssCreatedEvent in the backend and inherit ShouldBroadcast.

// 13. 创建 RssCreatedEvent 事件
php artisan make:event RssCreatedEvent
Copy after login

We use fake data and let it return the current time to facilitate viewing the effect:

<?php
namespace App\Events;
use Carbon\Carbon;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class RssCreatedEvent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }
    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        // 14. 创建频道
        return new Channel(&#39;rss&#39;);
    }
    /**
     * 指定广播数据。
     *
     * @return array
     */
    public function broadcastWith()
    {
        // 返回当前时间
        return [&#39;name&#39; => Carbon::now()->toDateTimeString()];
    }
}
Copy after login

Then we can make a scheduled task and let it broadcast every one minute:

protected function schedule(Schedule $schedule)
{
    // 15. 每隔一分钟执行一次
    $schedule->call(function () {
        event(new RssCreatedEvent());
    })->everyMinute();
}
Copy after login

Finally, let the home page load the vue component and refresh the test:

<!doctype html>
<html lang="{{ app()->getLocale() }}">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="csrf-token" content="{{ csrf_token() }}">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Laravel</title>
    </head>
    <body>
    <div id="app">
        <example-component></example-component>
    </div>
    <script src="{{ asset(&#39;js/app.js&#39;) }}"></script>
    </body>
</html>
Copy after login

Note: You need to introduce

<meta name="csrf-token" content="{{ csrf_token() }}">
Copy after login

in the header to compile the front end:

// 16. 运行 watch
yarn run watch-poll
Copy after login

Refresh the web page, Check the running effect:

Use Laravel Echo in 16 simple steps

As we wish, the broadcast is broadcast every one minute. The front-end laravel-echo listens and captures the broadcast, then reads the data and displays it.

Summary

So far, the technologies we have used are:

1. The use of laradock

2. Use of laravel echo server

3. Broadcast event

4.event() auxiliary function

5.$schedule scheduled task

6.Laravel Echo Use

We can basically use Laravel Echo. As for more in-depth use, it is recommended to check the official website documentation.

Finally, I strongly recommend you to use laradock to deploy the Docker development environment, because I believe laradock has prepared all the tools and environments you want to use for you.

The above is the detailed content of Use Laravel Echo in 16 simple steps. 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

Video Face Swap

Video Face Swap

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

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 to implement the custom table function of clicking to add data in dcat admin? How to implement the custom table function of clicking to add data in dcat admin? Apr 01, 2025 am 07:09 AM

How to implement the table function of custom click to add data in dcatadmin (laravel-admin) When using dcat...

How to get the return code when email sending fails in Laravel? How to get the return code when email sending fails in Laravel? Apr 01, 2025 pm 02:45 PM

Method for obtaining the return code when Laravel email sending fails. When using Laravel to develop applications, you often encounter situations where you need to send verification codes. And in reality...

Laravel Redis connection sharing: Why does the select method affect other connections? Laravel Redis connection sharing: Why does the select method affect other connections? Apr 01, 2025 am 07:45 AM

The impact of sharing of Redis connections in Laravel framework and select methods When using Laravel framework and Redis, developers may encounter a problem: through configuration...

Laravel multi-tenant extension stancl/tenancy: How to customize the host address of a tenant database connection? Laravel multi-tenant extension stancl/tenancy: How to customize the host address of a tenant database connection? Apr 01, 2025 am 09:09 AM

Custom tenant database connection in Laravel multi-tenant extension package stancl/tenancy When building multi-tenant applications using Laravel multi-tenant extension package stancl/tenancy,...

Laravel Eloquent ORM in Bangla partial model search) Laravel Eloquent ORM in Bangla partial model search) Apr 08, 2025 pm 02:06 PM

LaravelEloquent Model Retrieval: Easily obtaining database data EloquentORM provides a concise and easy-to-understand way to operate the database. This article will introduce various Eloquent model search techniques in detail to help you obtain data from the database efficiently. 1. Get all records. Use the all() method to get all records in the database table: useApp\Models\Post;$posts=Post::all(); This will return a collection. You can access data using foreach loop or other collection methods: foreach($postsas$post){echo$post->

How to effectively check the validity of Redis connections in Laravel6 project? How to effectively check the validity of Redis connections in Laravel6 project? Apr 01, 2025 pm 02:00 PM

How to check the validity of Redis connections in Laravel6 projects is a common problem, especially when projects rely on Redis for business processing. The following is...

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

Laravel database migration encounters duplicate class definition: How to resolve duplicate generation of migration files and class name conflicts? Laravel database migration encounters duplicate class definition: How to resolve duplicate generation of migration files and class name conflicts? Apr 01, 2025 pm 12:21 PM

A problem of duplicate class definition during Laravel database migration occurs. When using the Laravel framework for database migration, developers may encounter "classes have been used...

See all articles