Install the Package
composer require baks-dev/centrifugo
Verify PHP 8.4+ compatibility in your project.
Configure .env
Add Centrifugo connection details:
CENTRIFUGO_URL=ws://centrifugo:8000/connection/websocket
CENTRIFUGO_SECRET=your_secure_jwt_secret
CENTRIFUGO_REDIS_URL=redis://redis:6379
Install Assets Run the bundle installer:
php bin/console baks:assets:install
First Use Case: Publish an Event Dispatch a Centrifugo event from a Laravel controller or command:
use BaksDev\Centrifugo\Event\CentrifugoEvent;
event(new CentrifugoEvent('chat:room1', ['message' => 'Hello, world!']));
Frontend Integration Include the Centrifugo JS client in your frontend:
<script src="https://unpkg.com/centrifugo@latest/client.js"></script>
Connect to the WebSocket endpoint:
const client = new CentrifugoClient();
client.connect('ws://your-laravel-app/centrifugo/connection/websocket', {
token: 'user_jwt_token'
});
client.subscribe('chat:room1', (data) => {
console.log('Received:', data);
});
Event-Driven Pub/Sub
// In a controller or service
event(new CentrifugoEvent('notifications:user1', [
'type' => 'alert',
'message' => 'New message received'
]));
Private Channels
event(new CentrifugoEvent('private-user:{$userId}', ['data' => ...]));
client.subscribe(`private-user:${userId}`, (data) => { ... });
Presence Tracking
// In a Centrifugo config (if extended)
'presence': {
'enabled': true,
'max': 10000
}
client.presence('chat:room1').get((err, presence) => {
console.log('Users online:', presence);
});
Authentication
use BaksDev\Centrifugo\Facades\Centrifugo;
$token = Centrifugo::generateToken($userId, ['role' => 'admin']);
client.connect('ws://...', { token: 'generated_jwt_token' });
Laravel Events to Centrifugo Channels Create a mapping layer in a service:
class CentrifugoPublisher
{
public function publishToChannel(string $channel, array $data)
{
event(new CentrifugoEvent($channel, $data));
}
}
Queue Events for Scalability Dispatch Centrifugo events asynchronously:
event(new CentrifugoEvent(...))->dispatchSync(false);
Channel Management Dynamically create channels based on business logic:
$channel = "user:{$userId}:activity";
event(new CentrifugoEvent($channel, ['action' => 'login']));
Error Handling Catch and log Centrifugo exceptions:
try {
event(new CentrifugoEvent(...));
} catch (\BaksDev\Centrifugo\Exception\CentrifugoException $e) {
Log::error('Centrifugo error: ' . $e->getMessage());
}
Dependency Conflicts
baks-dev/centrifugo depends on baks-dev/core, which may introduce Symfony components not aligned with Laravel’s default stack. Run:
composer why baks-dev/core
to audit dependencies.Centrifugo Version Lock
Redis Configuration
Token Management
use BaksDev\Centrifugo\Facades\Centrifugo;
$token = Centrifugo::generateToken(
auth()->id(),
['roles' => auth()->user()->roles]
);
Frontend Connection Issues
CENTRIFUGO_URL in .env).allow_origin is configured).Channel Naming Collisions
private-*, presence-*).Centrifugo Logs
/var/log/centrifugo.log) for connection/auth issues:
journalctl -u centrifugo -f # If running as a service
Laravel Logging
'logging' => [
'channel' => 'single',
'level' => 'debug',
],
in config/centrifugo.php (if it exists).Network Inspection
wscat to test WebSocket connections:
wscat -c ws://your-centrifugo-url/connection/websocket
Redis Monitoring
redis-cli MONITOR
or use redis-cli --scan --pattern "*".Asset Installation
baks:assets:install command may fail if file permissions are restrictive. Run:
chmod -R 755 storage/bootstrap/cache
Environment Variables
CENTRIFUGO_SECRET is unique and securely stored (not hardcoded).Centrifugo Config Overrides
config.json) may require extending the package’s config. Check for extension points in the package’s Resources/config directory.Custom Event Handlers
CentrifugoEvent class to add metadata:
class CustomCentrifugoEvent extends CentrifugoEvent
{
public function __construct(string $channel, array $data, array $metadata = [])
{
parent::__construct($channel, array_merge($data, $metadata));
}
}
Middleware for Auth
// In a service provider
Centrifugo::extend(function ($app) {
$app->bind(\BaksDev\Centrifugo\Contracts\Authenticator::class, function () {
return new CustomAuthenticator();
});
});
Channel Filters
use BaksDev\Centrifugo\Contracts\ChannelFilter;
class UserChannelFilter implements ChannelFilter
{
public function allow(string $channel, string $userId): bool
{
return str_starts_with($channel, "private-user:{$userId}");
}
}
Metrics and Monitoring
// Example: Add a custom metric
Centrifugo::metrics(function () {
return [
'laravel_channels' => Centrifugo::getChannelCount(),
];
});
Batch Events
$batch = collect([...]);
event(new CentrifugoEvent('batch:channel', $batch->toArray()));
How can I help you explore Laravel packages today?