【问题标题】:Implementing Laravel 8 broadcasting with Pusher and Laravel Echo in a Vue frontend在 Vue 前端使用 Pusher 和 Laravel Echo 实现 Laravel 8 广播
【发布时间】:2021-07-02 03:18:44
【问题描述】:

我正在尝试使用 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 AM(1:56m 前) 主机名 Adefowowe-PC 状态失败 Job 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”,或者如何修复它。

或者如果它与用于接收/记录/显示广播消息的后续代码有关。

谢谢。

【问题讨论】:

    标签: vue.js laravel-8 pusher laravel-echo pusher-js


    【解决方案1】:

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

    【讨论】:

    • 升级到 8.29 解决了数组合并问题。谢谢@doydoy。
    猜你喜欢
    • 2017-04-15
    • 2019-09-14
    • 2020-06-14
    • 2023-03-10
    • 2018-08-17
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    相关资源
    最近更新 更多