首页 > 解决方案 > 无法使用 laravel websockets 获取数据库表更改的实时更新

问题描述

我第一次使用 Laravel websockets,我无法获得实时更新。我创建了自定义表单,用于保存用户的姓名和地址,将数据保存在表格中,并显示表格。我希望当任何其他用户填写表格并在表格中提交数据后,前端表格应该使用实时 laravel websockets 自动更新。但我发现了一些错误,请帮我完成这个。这是我的代码文件。

.env


    APP_NAME=Laravel
    APP_ENV=local
    APP_KEY=base64:G0y7BHQho3ZTwvL/FVOFZdc22Lz7yyJcnWRATDQu8LE=
    APP_DEBUG=true
    APP_URL=http://localhost
    
    LOG_CHANNEL=stack
    
    DB_CONNECTION=mysql
    DB_HOST=127.0.0.1
    DB_PORT=3306
    DB_DATABASE=testing_websocket
    DB_USERNAME=root
    DB_PASSWORD=
    
    BROADCAST_DRIVER=pusher
    CACHE_DRIVER=file
    QUEUE_CONNECTION=sync
    SESSION_DRIVER=file
    SESSION_LIFETIME=120
    
    REDIS_HOST=127.0.0.1
    REDIS_PASSWORD=null
    REDIS_PORT=6379
    
    MAIL_DRIVER=smtp
    MAIL_HOST=smtp.mailtrap.io
    MAIL_PORT=2525
    MAIL_USERNAME=null
    MAIL_PASSWORD=null
    MAIL_ENCRYPTION=null
    
    AWS_ACCESS_KEY_ID=
    AWS_SECRET_ACCESS_KEY=
    AWS_DEFAULT_REGION=us-east-1
    AWS_BUCKET=
    
    PUSHER_APP_ID=myId
    PUSHER_APP_KEY=myKey
    PUSHER_APP_SECRET=mySecret
    PUSHER_APP_CLUSTER=mt1
    
    MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
    MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

js\bootstrap.js


    window._ = require('lodash');
   
    
    try {
        window.Popper = require('popper.js').default;
        window.$ = window.jQuery = require('jquery');
    
        require('bootstrap');
    } catch (e) {}
    
    
    window.axios = require('axios');
    
    window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
        
    import Echo from 'laravel-echo';
    
    window.Pusher = require('pusher-js');
    
    window.Echo = new Echo({
        broadcaster: 'pusher',
        key: 'myKey',
        wsHost: window.location.hostname,
        wsPort: 6001,
        forceTLS: false,
        disableStats: true,
    });

配置\app.php


       App\Providers\BroadcastServiceProvider::class,

配置\广播.php


    <?php
    
    return [
    
        /*
        |--------------------------------------------------------------------------
        | Default Broadcaster
        |--------------------------------------------------------------------------
        |
        | This option controls the default broadcaster that will be used by the
        | framework when an event needs to be broadcast. You may set this to
        | any of the connections defined in the "connections" array below.
        |
        | Supported: "pusher", "redis", "log", "null"
        |
        */
    
        'default' => env('BROADCAST_DRIVER', 'null'),
    
        /*
        |--------------------------------------------------------------------------
        | Broadcast Connections
        |--------------------------------------------------------------------------
        |
        | Here you may define all of the broadcast connections that will be used
        | to broadcast events to other systems or over websockets. Samples of
        | each available type of connection are provided inside this array.
        |
        */
    
        'connections' => [
    
            'pusher' => [
                'driver' => 'pusher',
                'key' => env('PUSHER_APP_KEY'),
                'secret' => env('PUSHER_APP_SECRET'),
                'app_id' => env('PUSHER_APP_ID'),
                'options' => [
                    'cluster' => env('PUSHER_APP_CLUSTER'),
                    'useTLS' => true,
                    'host' => '127.0.0.1',
                    'port' => 6001,
                    'scheme' => 'http'
                ],
            ],
    
            'redis' => [
                'driver' => 'redis',
                'connection' => 'default',
            ],
    
            'log' => [
                'driver' => 'log',
            ],
    
            'null' => [
                'driver' => 'null',
            ],
    
        ],
    
    ];

form.blade.php


    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Form</title>
    </head>
    <body>
            <form method="POST" action="{{route('FormSubmit')}}">
                {{csrf_field()}}
                Name: <input type="text" name="uname" /> <br>
                Address: <input type="text" name="add" /> <br>
                <input type="submit" name="submit"/>
            </form>
    </body>
    </html>


table.blade.php


    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    <body>
        <table border="1">
            <tr>
                <td>
                    Name
                </td>
                <td>
                    Email
                </td>
            </tr>
            @foreach ($data as $print)
               
            <tr>
                <td>
                    {{$print['name']}}
                </td>
                <td>
                    {{$print['address']}}
                </td>
            </tr>
            @endforeach
        </table>
    </body>
    </html>
    
    <script>
        Echo.channel('post')
            .listen('NewUser', (e) => console.log('NewUser: ' + e.name, 'Address:' + e.address));
    </script>

事件\NewUser.php


    <?php
    
    namespace App\Events;
    
    use App\User;
    use App\Testing;
    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;
    use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
    
    class NewUser implements ShouldBroadcastNow
    {
        use Dispatchable, InteractsWithSockets, SerializesModels;
    
            public $name;
            public $address;
        /**
         * Create a new event instance.
         *
         * @return void
         */
        public function __construct(Name $name, Address $address)
        {
            $this->name = $name;
            $this->address = $address;
            //
        }
    
        /**
         * Get the channels the event should broadcast on.
         *
         * @return \Illuminate\Broadcasting\Channel|array
         */
        public function broadcastOn(): Channel
        {
            return new Channel('post');
        }
    }


标签: phplaravelreal-timepusher-jslaravel-websockets

解决方案


推荐阅读