I'm using laravel 8, and I'm having a hard time getting the data from the event using pusher. I'm want to broadcast the event, i want to receive the data when the data is successfully inserted in the database. hope someone can help me with this. here are my codes
config/app.php
/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class
Events\Chat.php
class Chat implements ShouldBroadcastNow
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*
* @return void
*/
public $data;
public function __construct($data)
{
$this->data = $data;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel('chat');
}
public function broadcastAs()
{
return 'get-chat';
}
}
chat.blade.php
var pusher = new Pusher('dec355f1ff67f51f5784', {
cluster: 'ap1',
forceTLS: true
});
Pusher.logToConsole = true;
$('.chat-send').click(function(){
var msg = $('.chat-msg').val();
$.ajax({
url: add_url,
type: 'POST',
data: {'msg' : msg},
dataType: 'json',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
success: function(data) {
if (data.msg == 'success') {
var channel = pusher.subscribe('chat');
channel.bind('pusher:subscription_succeeded', function(data) {
//alert('successfully subscribed!');
console.log(data);
});
channel.bind('get-chat', function(data) {
//console.log(JSON.stringify(data));
alert(data);
});
}
},
error : function(request, status, error) {
//swal("Oops!", "Seems like there is an error. Please try again", "error");
}
});
});
MessageController
public function create(Request $request, Messages $messages)
{
$request->merge([
'teacher_id' => 2,
'student_id' => 1,
'message' => 'test msg'
]);
$data = $messages::create($request->all());
if ($data->exists) {
$msg = 'success';
$cars = ['hey', 'yow'];
broadcast(new Chat($cars));
}
return json_encode(['msg'=>$msg]);
}
This is what I get in the pusher.log
Pusher : : ["Event sent",{"event":"pusher:subscribe","data":{"auth":"","channel":"chat"}}]
Pusher : : ["Event recd",{"event":"pusher_internal:subscription_succeeded","channel":"chat","data":{}}]