嗨,我在发送消息时正在项目中使用Laravel推入器和回显服务,消息正在广播并在控制台的puhser中显示,但未在其他登录屏幕中显示,实时无法正常工作。 这是我的消息课程
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Events\NewMessage;
class Message extends Model
{
protected $dispatchesEvents = [
'created' => NewMessage::class
];
protected $fillable = [
'from', 'to', 'text'
];
}
这是我的频道
Broadcast::channel('messages.{id}', function ($user, $id) {
return $user->id === (int) $id;
});
这是我的控制人
public function sendmessage(Request $request)
{
$message=Message::create([
'from'=>Auth::user()->id,
'to'=>$request->contact_id,
'text'=>$request->text,
]);
return response()->json($message);
}
这是我的活动
<?php
namespace App\Events;
use App\Message;
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;
class NewMessage implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(Message $message)
{
$this->message=$message;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
// dd($this->message->to);
return new PrivateChannel('messages.'.$this->message->to);
}
public function broadcastWith()
{
return ["message" => $this->message];
}
}
这是我的组件
mounted() {
Echo.private(`messages.${this.user.id}`)
.listen('NewMessage', (e) => {
console.log(e);
this.hanleIncoming(e.message);
});
console.log('Component mounted.')
axios.get('/getContacts').then((response)=>{
this.contacts=response.data;
console.log(this.contacts);
});
},