Hello everybody,
Actually I am still working on my private messaging app.
To load new notifications, I would like to use a PrivateChannel.
This is what I'm doing at the moment:
bootstrap.js
import Echo from 'laravel-echo'
window.io = require('socket.io-client');
window.Echo = new Echo({
broadcaster: 'socket.io',
host: window.location.hostname + ':6001'
});
window.Echo.private('conversation.${messageId}')
.listen('MessageCreated', (e) => {
console.log(e);
});
MessageChannel.php
<?php
namespace App\Broadcasting;
use App\User;
use App\Message;
use Illuminate\Support\Facades\Log;
class MessageChannel
{
/**
* Create a new channel instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* @param \App\User $user
* @param \App\Message $message
*
* @return bool
*/public function join(User $user, Message $message)
{
return $user->id === $message->user_id;
}
}
MessageCreated.php
<?php
namespace App\Events;
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 Cmgmyr\Messenger\Models\Message;
class MessageCreated implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
/**
* MessageCreated constructor.
*
* @param \App\Message $message
*/
public function __construct(Message $message)
{
$this->message = $message;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('conversation.'.$this->message->id);
}
}
channels.php
Broadcast::channel('conversation.{messageId}', function($user, $messageId){
return Auth::check(); //has to be improved. Check, whether the user is in recipients list
});
web.php (test route)
Route::get('test', function(){
$message = App\Message::find(1);
broadcast(new \App\Events\MessageCreated($message));
});
Now I'm getting this in my Echo console:
[13:44:07] - Sending auth request to: https://test.app/broadcasting/auth
[13:44:10] - Do63uEo-ePk8Nh9jAAC0 authenticated for: private-conversation.${messageId}
[13:44:10] - Do63uEo-ePk8Nh9jAAC0 joined channel: private-conversation.${messageId}
I got this from https://laravel.com/docs/5.7/broadcasting -> Listening For Event Broadcasts
Echo.private(`order.${orderId}`)
.listen('ShippingStatusUpdated', (e) => {
console.log(e.update);
});
But where does Echo.private get ${orderId} from in this example?