> ## Documentation Index
> Fetch the complete documentation index at: https://chorus.pixelsprout.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Harmonics

> Understand harmonics - the core concept behind Laravel Chorus's real-time synchronization system.

# 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

```php theme={null}
// 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

<Steps>
  <Step title="Change Detection">
    When a model with the `Harmonics` trait is modified, Laravel's model events automatically detect the change:

    ```php theme={null}
    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
    ]);
    ```
  </Step>

  <Step title="Harmonic Creation">
    The trait's event listeners create a harmonic record.
  </Step>

  <Step title="Broadcasting">
    The harmonic is immediately broadcast via WebSocket to connected clients.
  </Step>

  <Step title="Client Processing">
    Connected clients receive the harmonic and update their local IndexedDB.
  </Step>
</Steps>

## Data Filtering in Harmonics

### Field Filtering

Only fields defined in `$syncFields` are included in harmonic data:

```php theme={null}
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

<AccordionGroup>
  <Accordion title="Minimize Harmonic Data" icon="compress">
    * Only sync essential fields
    * Use computed fields sparingly
    * Avoid large text or binary data
    * Consider separate models for large content
  </Accordion>

  <Accordion title="Efficient Filtering" icon="filter">
    * Use database indexes for sync filters
    * Avoid complex relationship queries in filters
    * Cache expensive filter computations
    * Use appropriate data types for filter fields
  </Accordion>

  <Accordion title="Batch Operations" icon="layer-group">
    * Use bulk operations when possible
    * Implement batch harmonic creation for imports
    * Consider background processing for large datasets
    * Use database transactions for consistency
  </Accordion>
</AccordionGroup>

### Security Considerations

<AccordionGroup>
  <Accordion title="Field Security" icon="shield-check">
    * Never sync sensitive data (passwords, tokens)
    * Validate sync fields at runtime
    * Use field whitelisting, not blacklisting
    * Regular security audits of synced data
  </Accordion>

  <Accordion title="User Isolation" icon="users">
    * Always implement sync filters for user data
    * Validate user permissions in filters
    * Use tenant-based isolation for multi-tenant apps
    * Test authorization thoroughly
  </Accordion>

  <Accordion title="Data Validation" icon="check-circle">
    * Validate harmonic data before broadcasting
    * Sanitize data for client consumption
    * Implement server-side validation for all operations
    * Use type checking for harmonic payloads
  </Accordion>

  <Accordion title="Authorization Policies" icon="lock">
    * Use Laravel policies to control harmonic access
    * Implement view() method to filter unauthorized harmonics
    * Leverage existing authorization logic
    * Automatic rejection of unauthorized changes
  </Accordion>
</AccordionGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Write Path" href="/concepts/write-path" icon="pen">
    Learn how client writes are processed and validated
  </Card>

  <Card title="Shadow Tables" href="/concepts/write-path#shadow-and-delta-tables" icon="database">
    Understand offline synchronization with shadow tables
  </Card>

  <Card title="React Integration" href="/integrations/react" icon="react">
    Use harmonics in your React components
  </Card>

  <Card title="Advanced Features" href="/advanced/channel-prefixes" icon="gear">
    Explore advanced harmonic routing and channels
  </Card>
</CardGroup>

***

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.
