// routes/channels.php
// IMPORTANT. In Centrifugo 4, the '$' character in front of the private channel is considered obsolete. Do not use it. https://centrifugal.dev/docs/server/channels#private-channel-prefix-
Broadcast::channel('namespace:channel', function (){
// Some auth logic for example:
return \Auth::user()->group === 'private-channel-group';
});
Broadcast::channel('namespace:channel-{id}', function ($user, $id){
return $user->id === $id;
});
// App/Events/SendMessageEvent.php
namespace App\Events;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
//Use "implements ShouldBroadcast" if you want add event to queue
class SendMessageEvent implements ShouldBroadcastNow
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* @var string Message text
*/
private $messageText;
public function __construct(string $messageText)
{
$this->messageText = $messageText;
}
/**
* The event's broadcast name.
*
* @return string
*/
public function broadcastAs()
{
//example event broadcast name. Show in Web Socket JSON
return 'message.new';
}
/**
* Get the data to broadcast.
*
* @return array
*/
public function broadcastWith()
{
return ['message' => $this->messageText];
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel('public:chat');
// or return new PrivateChannel('private:chat');
// in Centrifuge 4 all channels are protected, and the '$' prefix is considered obsolete. https://centrifugal.dev/docs/server/channels#private-channel-prefix-
}
}
declare(strict_types = 1);
namespace App\Http\Controllers;
use Opekunov\Centrifugo\Centrifugo;
use Illuminate\Support\Facades\Auth;
class ExampleController
{
public function example(Centrifugo $centrifugo)
{
//or $centrifugo = new Centrifugo();
//or centrifugo()
// Send message into channel
$centrifugo->publish('news', ['message' => 'Hello world']);
// Generate connection token
$token = $centrifugo->generateConnectionToken((string)Auth::id(), 0, [
'name' => Auth::user()->name,
]);
// Generate subscription token
$expire = now()->addDay(); //or you can use Unix: $expire = time() + 60 * 60 * 24;
$apiSign = $centrifugo->generateSubscriptionToken((string)Auth::id(), 'channel', $expire, [
'name' => Auth::user()->name,
]);
//Get a list of currently active channels.
$centrifugo->channels();
//Get channel presence information (all clients currently subscribed on this channel).
$centrifugo->presence('news');
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.