Laravel广播频道功能不会激发

So I'm gonna use laravel broadcasting for a chat app,

I followed Laravel Broadcasting approach,

  • Uncommented App\Providers\BroadcastServiceProvider from providers array inside config/app.php

  • Registered in pusher website, made a channel and filled the fields below inside .env file with my pusher channel info

PUSHER_APP_ID
PUSHER_APP_KEY
PUSHER_APP_SECRET
PUSHER_APP_CLUSTER
  • Inside my broadcast.php config file where I set the default driver to pusher, I also added
'options' => [
    'cluster' => 'us2',
    'encrypted' => true,
],

to pusher array inside connections array based on my channel info in pusher panel

  • Installed pusher php package on my laravel project using composer require pusher/pusher-php-server "~3.0" command

Here is my event class

<?php

namespace App\Events;
use App\User;
use App\TherapyMessage;
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 App\AppLog;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;

class TherapyMessageSent implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**
     * User that sent the message
     *
     * @var User
     */
    public $user;

    /**
     * Message details
     *
     * @var Message
     */
    public $message;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(User $user, TherapyMessage $message)
    {
        $this->user = $user;
        $this->message = $message;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return Channel|array
     */
    public function broadcastOn()
    {
        $message_id = $this->message->id;
        $user = $this->user;

        AppLog::create([
            'file_name' => __FILE__,
            'message' => "broadcast before send with Message ID of $message_id from $user->full_name"
        ]);

        return new PrivateChannel("therapy-chat.$message_id");
    }
}

  • The AppLog is a model that I use for logging inside the project
  • I tried implementing ShouldBroadcast interface at first but that didn't work either
  • I also registered my event inside EventServiceProvider.php file and run php artisan event:generate command, here is the EventServiceProvider $listen array:
protected $listen = [
    Registered::class => [
        SendEmailVerificationNotification::class,
        TherapyMessageSent::class
    ],
];

I also imported the event namespace next to other namespaces inside the file: use \App\Events\TherapyMessageSent;

Here is the channel that I defined inside routes/channels.php file:


use App\AppLog;

Broadcast::channel('therapy-chat.{message_id}', function ($user, $message_id) {

    AppLog::create([
        'file_name' => __FILE__,
        'message' => "broadcast sending with Message ID of $message_id to $user->full_name"
    ]);

    if (!Auth::check()) return false;

    $message = \App\TherapyMessage::find($message_id);

    if (!$message) {

        AppLog::create([
            'file_name' => __FILE__,
            'message' => "Message with ID of $message_id Not Found for broadcasting"
        ]);

        return false;
    }

    $will_send = false;

    if ($therapist = $user->therapist) {
        $will_send = $therapist->id === $message->therapist_id;
    } else if ($patient = $user->patient) {
        $will_send = $message->patient_id === $patient->id;
    }

    if ($will_send) {

        AppLog::create([
            'file_name' => __FILE__,
            'message' => "Message with ID of $message_id broadcasted to $user->full_name"
        ]);
    }

    return $will_send;
});

Finally, this is my controller method:

public function sendToTherapist(Request $request) {

    $validation = \Validator::make($request->all(), ['message' => 'required']);

    if ($validation->fails()) return $this->validationError($validation);

    $user = \Auth::user();
    $patient = $user->patient;
    $therapist = $patient->therapist;

    if (!$therapist) return $this->errorWithMessage('Patient does not have Therapist');

    $message = \App\TherapyMessage::create([
        'patient_id' => $patient->id,
        'therapist_id' => $therapist->id,
        'type' => TherapyMessageType::TEXT,
        'text' => $request->message,
        'sender_role' => TherapyMessageSenderRole::PATIENT
    ]);

    broadcast(new TherapyMessageSent($user, $message))->toOthers();

    return $this->success(['id' => $message->id]);
}
  • My controller class extends from BaseController which is a custom controller class with helper methods such as success(), validationError() and errorWithMessage()

As you see in the code above I filled $user and $message with correct values and the request works without any error

I think the channel method won't even be fired, as I check the AppLog table when I call broadcast method, only the log inside TherapyMessageSent event broadcastOn function is saved and even the log that I save at the beginning of channels.php method, isn't saved so I think this method is never executed.

If anyone could help me with the problem, I'd be thankful.

dongxiee0744
dongxiee0744 观看这些系列laracasts.com/series/get-real-with-laravel-echolaracasts.com/lessons/introducing-laravel-echobytaylorandjeffrey
一年多之前 回复
dongque1958
dongque1958 我不知道它是否会返回任何内容,我实际上不知道它是如何工作的但我所看到的只是通道功能不会执行
一年多之前 回复
dqusbxh44823
dqusbxh44823 队列驱动程序是数据库,我认为这是默认的
一年多之前 回复
dongyanghan0556
dongyanghan0556 你说它不工作所以它什么都不返回?也发布你的前端
一年多之前 回复
dongshi1215
dongshi1215 队列驱动默认?
一年多之前 回复
dongweizhen2009
dongweizhen2009 我没有得到你的确切,删除toOthers()并检查broadcast()返回什么?如果是这样,它返回一个Illuminate\Broadcasting\PendingBroadcast实例,当我尝试使用serialize()或eval()将其转换为字符串以查看实际值时,它会抛出异常,说不允许序列化'闭包',顺便说一下,它返回的重要性是什么?
一年多之前 回复
dongyi5070
dongyi5070 也请关注laracasts.com/series/get-real-with-laravel-echo和laracasts.com/lessons/introducing-laravel-echo
一年多之前 回复
douzhang5121
douzhang5121 你可以删除toOthers并检查它是否会向你返回任何东西(带病人的auth用户)
一年多之前 回复
doucong1853
doucong1853 我刚刚在问题中添加了完整的控制器方法
一年多之前 回复
drd43058
drd43058 是的,事件就像我提到的那样触发,但是当它调用PrivateChannel时(“therapy-chat。$message_id”);channel.php中的方法不会被触发,我将从TherapyMessageSent文件中保存的日志被创建,我可以从DB看到它们但是channel.php中的日志将不会被保存,这就是为什么我认为这个方法内部channel.php甚至不会被执行
一年多之前 回复
dpwfh874876
dpwfh874876 你能分享你在哪里发起TherapyMessageSent事件的控制器吗?
一年多之前 回复
doumaikuang4202
doumaikuang4202 你的队列工作者是否正在运行(phpartisanqueue:work)?来自docs:“...然后,你只需像往常一样触发事件。一旦事件被触发,排队的作业将自动通过指定的广播驱动程序广播事件。”
一年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐