I am trying to create a match making system. When a match is found, I want to broadcast to the user the match was found for. I can’t figure this out - should I use polling instead?
My User model has a belongsToMany relationship with a Match model.
Heres my code that does not work.
Route:
Broadcast::channel('match.{matchId}', function ($user, $matchId) {
return $user->matches()->contains('id', $matchId);
});
Component:
class PlayComponent extends Component
{
public $matchId;
public function getListeners()
{
return [
"echo-private:match.{$this->matchId},JoinMatch" => 'joinMatch',
];
}
public function render()
{
return view('livewire.play-component', [
'matches' => Auth::user()->matches()->get()->toArray(),
]);
}
public function play()
{
if ($match = Match::where('status', 'waiting')->first()) {
$this->matchId = $match->id;
event(new JoinMatch($match));
}
else {
$this->matchId = Auth::user()->matches()->create(['status' => 'waiting']);
}
}
public function joinMatch()
{
// ???
}
}
View:
<div>
<button class="btn btn-success" wire:click="play">Play</button>
<hr>
<pre>{{ print_r($matches, true) }}</pre>
</div>
Event:
class JoinMatch implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $match;
public function __construct(Match $match)
{
$this->match = $match;
$this->match->users()->attach(Auth::user()->id);
}
public function broadcastOn()
{
return new PrivateChannel('match.' . $this->match->id);
}
}
How do I make this work? I think the problem is getListeners
expects a parameter, but this parameter may not exist for the matched user yet.