在 Vue 前端使用 Pusher 和 Laravel Echo 实现 Laravel 8 广播

如何解决在 Vue 前端使用 Pusher 和 Laravel Echo 实现 Laravel 8 广播

我正在尝试使用 Laravel 实现事件广播和通知。目标是通过通知向登录用户广播私人消息。

我创建了这个事件,见下面的代码:

<?php

namespace App\Events;

use App\Models\User;
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 TradingAccountActivation implements ShouldBroadcast
{
    use Dispatchable,InteractsWithSockets,SerializesModels;

     /**
     * The authenticated user.
     *
     * @var \Illuminate\Contracts\Auth\Authenticatable
     */
    public $user;
    public $message;

    /**
     * Create a new event instance.
     *
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
     * @return void
     */
    public function __construct(User $user)
    {
        $this->user = $user;
        $this->message = "{$user->first_name} is ready to trade";
    }

   
    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('user.'.$this->user->id);
    }

}

每个新验证的用户都会触发该事件,因此我将事件放在项目的电子邮件验证控制器中,请参阅以下代码:

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Auth\Events\Verified;
use App\Events\TradingAccountActivation;
use Illuminate\Foundation\Auth\EmailVerificationRequest;
class VerifyEmailController extends Controller
{
    /**
     * Mark the authenticated user's email address as verified.
     *
     * @param  \Illuminate\Foundation\Auth\EmailVerificationRequest  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function __invoke(EmailVerificationRequest $request)
    {
        if ($request->user()->hasVerifiedEmail()) {
            return redirect()->intended(RouteServiceProvider::HOME.'?verified=1');
        }

        if ($request->user()->markEmailAsVerified()) {
            event(new Verified($request->user()));
        } 

        event(new TradingAccountActivation($request->user()));
        return redirect()->intended(RouteServiceProvider::HOME.'?verified=1');
           
    }
}

此时事件失败并显示以下错误消息:

ErrorException
array_merge(): Expected parameter 2 to be an array,null given

堆栈跟踪指向带有星号的行上的 pusher:

Illuminate\Foundation\Bootstrap\HandleExceptions::handleError
C:\xampp\htdocs\spa\vendor\pusher\pusher-php-server\src\Pusher.php:391

        $path = $this->settings['base_path'].'/events';

         // json_encode might return false on failure

        if (!$data_encoded) {

            $this->log('Failed to perform json_encode on the the provided data: {error}',array(

                'error' => print_r($data,true),),LogLevel::ERROR);

        }

         $post_params = array();

        $post_params['name'] = $event;

        $post_params['data'] = $data_encoded;

        $post_params['channels'] = array_values($channels);

    *    $all_params = array_merge($post_params,$params);

         $post_value = json_encode($all_params);

         $query_params['body_md5'] = md5($post_value);

Laravel Telescope 确认事件失败并提供以下详细信息:

工作详情 时间 2021 年 4 月 6 日,上午 9:05:01(1:56 前) 主机名 Adefowowe-PC 状态失败 工作 App\Events\TradingAccountActivation 连接同步 队列
尝试 - 超时 - 标签 App\Models\User:75Auth:75failed 认证用户 身份证 75 电子邮件地址 j@doe.com

连同事件要发出的数据:

{
"event": {
"class": "App\Events\TradingAccountActivation","properties": {
"user": {
"id": 75,"uuid": "75da67ef-d6f8-4cd0-9d57-e1dcf66c1f5e","first_name": "John","last_name": "Doe","mobile_phone_number": "08033581133","verification_code": null,"phone_number_isVerified": 0,"phone_number_verified_at": null,"email": "j@doe.com","email_verified_at": "2021-04-06T08:04:49.000000Z","created_at": "2021-04-06T08:03:56.000000Z","updated_at": "2021-04-06T08:04:49.000000Z"
},"message": "John is ready to trade","socket": null
}
},"tries": null,"timeout": null,"connection": null,"queue": null,"chainConnection": null,"chainQueue": null,"chainCatchCallbacks": null,"delay": null,"afterCommit": null,"middleware": [
],"chained": [
]
}

奇怪的是,尽管事件失败,但似乎广播频道已创建并已建立连接。刷新错误页面似乎继续控制器的下一个操作,即重定向到经过身份验证的用户的仪表板。此时建立广播连接。请参阅下面的 Laravel Telescope 详细信息以及有效负载:

Request Details
Time    April 6th 2021,10:02:38 AM (10s ago)
Hostname    Adefowowe-PC
Method  POST
Controller Action   \Illuminate\Broadcasting\BroadcastController@authenticate
Middleware  auth:web
Path    /broadcasting/auth
Status  302
Duration    1043 ms
IP Address  127.0.0.1
Memory usage    12 MB
Payload
Headers
Session
Response
{
"socket_id": "131623.12865758","channel_name": "private-user.${this.user.id}"
}

由于事件失败,我没想到会建立一个广播通道,或者为后续的侦听器和通知广播消息触发。

我无法弄清楚事件失败的原因,即如何处理异常“array_merge(): Expected parameter 2 to be an array,null given”,或者如何修复它。

或者是否与接收/记录/显示广播消息的后续代码有关。

谢谢。

解决方法

此问题已在 8.29.0 版本中解决。您需要升级到指定的版本,或者降级 pusher-http-php (composer require pusher/pusher-php-server ^4.1)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res