duanpuqi9965 2019-05-11 20:04
浏览 237

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.

  • 写回答

0条回答

    报告相同问题?

    悬赏问题

    • ¥20 双层网络上信息-疾病传播
    • ¥50 paddlepaddle pinn
    • ¥20 idea运行测试代码报错问题
    • ¥15 网络监控:网络故障告警通知
    • ¥15 django项目运行报编码错误
    • ¥15 请问这个是什么意思?
    • ¥15 STM32驱动继电器
    • ¥15 Windows server update services
    • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
    • ¥15 模糊pid与pid仿真结果几乎一样