Harmonics

Harmonics are the fundamental units of change in Laravel Chorus. Every create, update, or delete operation on a synchronized model generates a harmonic record that captures what changed and broadcasts it to connected clients.

What is a Harmonic?

A harmonic is a change record stored in the harmonics database table that contains:
  • What changed - The table name and record ID
  • How it changed - The operation type (create/update/delete)
  • The new data - JSON payload of the synchronized fields
  • Who can see it - Optional user_id for scoped synchronization (mainly used for rejected harmonics)
  • When it happened - Timestamp for ordering and deduplication
// Example harmonic record
{
    "id": 1,
    "table_name": "messages",
    "record_id": "123",
    "operation": "create",
    "data": {
        "id": "123",
        "body": "Hello world!",
        "user_id": 1,
        "created_at": "2024-01-15T10:30:00Z"
    },
    "user_id": 1,
    "created_at": "2024-01-15T10:30:00Z"
}

The Harmonic Lifecycle

1. Change Detection

1

Change Detection

When a model with the Harmonics trait is modified, Laravel’s model events automatically detect the change:
class Message extends Model
{
    use Harmonics;

    protected $syncFields = ['id', 'body', 'user_id'];
}

// This triggers harmonic creation
$message = Message::create([
'body' => 'Hello world!',
'user_id' => 1
]);
2

Harmonic Creation

The trait’s event listeners create a harmonic record.
3

Broadcasting

The harmonic is immediately broadcast via WebSocket to connected clients.
4

Client Processing

Connected clients receive the harmonic and update their local IndexedDB.

Data Filtering in Harmonics

Field Filtering

Only fields defined in $syncFields are included in harmonic data:
class User extends Model
{
    use Harmonics;
    
    // Only these fields will appear in harmonics
    protected $syncFields = [
        'id',
        'name', 
        'email',
        'avatar_url'
        // 'password' excluded for security
        // 'remember_token' excluded for security
    ];
}

Best Practices

Performance Optimization

Security Considerations

Next Steps


Harmonics are the foundation that makes Laravel Chorus’s real-time synchronization possible. Understanding how they work will help you design efficient, secure, and scalable real-time applications.