Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Ux Live Component Laravel Package

symfony/ux-live-component

Build interactive UIs in Symfony with Live Components: stateful server-driven components that update via Ajax without writing much JavaScript. Integrates with Twig, Stimulus and Symfony UX for reactive forms, lists, and real-time interactions.

Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require symfony/ux-live-component
    

    Ensure your Symfony app is on v6.3+ (or v7.0+ for latest features).

  2. Enable Live Components In config/packages/ux_live_component.yaml, enable the bundle:

    framework:
        ux_live_component:
            enabled: true
    
  3. First Live Component Create a basic component in src/Components/ExampleComponent.php:

    namespace App\Component;
    
    use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
    use Symfony\UX\LiveComponent\DefaultActionTrait;
    
    #[AsLiveComponent('example')]
    class ExampleComponent
    {
        use DefaultActionTrait;
    
        public string $name = 'World';
    
        public function greet(): string
        {
            return "Hello, {$this->name}!";
        }
    }
    
  4. Render in Twig Use the component in a Twig template (templates/example.html.twig):

    {{ component('example') }}
    

    Or inline:

    {{ component('example', { name: 'Alice' }) }}
    
  5. Trigger Updates Use JavaScript to update the component:

    // In your asset (e.g., app.js)
    import { startStimulusApp } from '@symfony/stimulus-bridge';
    startStimulusApp();
    
    // Or manually trigger updates
    document.querySelector('[data-controller="live"]').action('update');
    

Implementation Patterns

1. State Management

  • Reactive Properties: Declare properties with #[LiveProp] to auto-trigger updates:
    #[LiveProp]
    public int $count = 0;
    
  • Actions: Define methods with #[LiveAction] to handle user interactions:
    #[LiveAction]
    public function increment(): void
    {
        $this->count++;
    }
    
    Call from Twig:
    <button {{ action('increment') }}>+</button>
    

2. Composition

  • Nested Components: Embed components within others:
    #[AsLiveComponent('parent')]
    class ParentComponent
    {
        public ChildComponent $child;
    }
    
    Twig:
    {{ component('child') }}
    

3. Data Fetching

  • Async Actions: Use #[LiveAction] with use Symfony\UX\LiveComponent\Attribute\LiveAction for async operations:
    #[LiveAction]
    public function fetchData(): void
    {
        $data = $this->fetchFromApi(); // Simulate API call
        $this->data = $data;
    }
    
    Twig:
    <button {{ action('fetchData') }}>Load Data</button>
    

4. Forms Integration

  • Live Forms: Use #[LiveComponent] with Symfony Forms:
    use Symfony\Component\Form\Extension\Core\Type\TextType;
    
    #[AsLiveComponent('form_example')]
    class FormComponent
    {
        public function buildForm(): void
        {
            $this->form = $this->createFormBuilder()
                ->add('name', TextType::class)
                ->getForm();
        }
    }
    
    Twig:
    {{ form_start(form) }}
        {{ form_widget(form) }}
    {{ form_end(form) }}
    

5. Stimulus Integration

  • Custom Controllers: Extend functionality with Stimulus:
    // assets/controllers/example_controller.js
    import { Controller } from '@hotwired/stimulus';
    
    export default class extends Controller {
        connect() {
            console.log('Component connected!');
        }
    }
    
    Twig:
    <div {{ stimulus('example') }}>
        {{ component('example') }}
    </div>
    

6. Server-Side Rendering (SSR)

  • Hybrid Rendering: Use #[LiveComponent] for SSR + client-side hydration:
    #[AsLiveComponent('hybrid')]
    class HybridComponent
    {
        public function renderInEnvironment(Environment $environment): string
        {
            return match ($environment) {
                Environment::SERVER => 'Server-rendered HTML',
                Environment::CLIENT => 'Client-side HTML',
            };
        }
    }
    

Gotchas and Tips

Common Pitfalls

  1. Circular Dependencies

    • Avoid circular references between components (e.g., A uses B, B uses A). Use dependency injection or lazy-loading.
  2. State Not Updating

    • Ensure properties are marked with #[LiveProp] or are public. Private properties won’t trigger updates.
    • Check for JavaScript errors in the browser console (e.g., Stimulus not loaded).
  3. Form Submission Issues

    • Live forms require enctype="multipart/form-data" for file uploads.
    • Use {{ form_errors(form) }} to debug form validation errors.
  4. Stimulus Not Working

    • Verify @symfony/stimulus-bridge is installed and imported in your JS entrypoint.
    • Ensure data-controller attributes are correctly set in Twig.
  5. Performance with Large Data

    • Use #[LiveProp(write: false)] for read-only properties to reduce payload size.
    • Paginate or lazy-load data in #[LiveAction] methods.

Debugging Tips

  • Log Component State:
    #[LiveAction]
    public function debug(): void
    {
        error_log(print_r($this->getState(), true));
    }
    
  • Check Network Requests:
    • Open DevTools (F12) → Network tab to inspect live component updates (look for /_live_component endpoints).
  • Disable Caching: For development, disable Symfony’s HTTP cache to see real-time updates:
    # config/packages/dev/framework.yaml
    framework:
        http_cache:
            enabled: false
    

Advanced Patterns

  1. Custom Hydration Override hydrate() to initialize state from client-side data:

    public function hydrate(array $data): void
    {
        $this->name = $data['name'] ?? 'Guest';
    }
    
  2. WebSocket Integration Use #[LiveAction] with Symfony Messenger or Mercure to push updates:

    #[LiveAction]
    public function subscribe(): void
    {
        $this->dispatch(new SubscribeToUpdatesEvent());
    }
    
  3. Type Safety Use PHP 8.2+ attributes for stricter typing:

    #[LiveProp(type: 'int')]
    public int $count = 0;
    
  4. Testing Test components with LiveComponentTestCase:

    use Symfony\UX\LiveComponent\Test\LiveComponentTestCase;
    
    class ExampleComponentTest extends LiveComponentTestCase
    {
        public function testGreet(): void
        {
            $component = $this->createComponent(ExampleComponent::class);
            $this->assertSelectorTextContains('h1', 'Hello, World!');
        }
    }
    

Configuration Quirks

  • Endpoint Customization: Change the live component endpoint in config/packages/ux_live_component.yaml:
    framework:
        ux_live_component:
            endpoint: /api/live
    
  • CSRF Protection: Live components auto-disable CSRF for GET/HEAD requests. For POST, ensure CSRF tokens are included in forms.

Extension Points

  1. Custom Serializer Extend LiveComponentSerializer to modify payloads:

    use Symfony\UX\LiveComponent\Serializer\LiveComponentSerializer;
    
    class CustomSerializer extends LiveComponentSerializer
    {
        protected function serializeState(array $state): array
        {
            // Custom logic
            return parent::serializeState($state);
        }
    }
    

    Register in services:

    services:
        Symfony\UX\LiveComponent\Serializer\LiveComponentSerializer:
            class: App\Serializer\CustomSerializer
    
  2. Event Listeners Listen to component lifecycle events:

    use Symfony\UX\LiveComponent\Event\LiveComponentEvent;
    
    class MyListener
    {
        public function onComponentRendered(LiveComponentEvent $event): void
        {
            $event->getComponent()->log('Rendered!');
        }
    }
    

    Register in services.yaml:

    services:
        App\Listener\MyListener:
            tags:
                - { name: 'kernel.event_listener', event: 'ux.live_component.rendered' }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport