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

Livewire Laravel Package

wpstarter/livewire

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require wpstarter/livewire
    

    Ensure your WordPress theme is built on the WpStarter framework (this package is a dependency of WpStarter).

  2. Enqueue Livewire Scripts In your theme's functions.php or a custom plugin:

    add_action('wp_enqueue_scripts', function() {
        wp_enqueue_script('livewire');
    });
    
  3. First Livewire Component Create a component at wp-content/themes/your-theme/app/Livewire/YourComponent.php:

    <?php
    namespace App\Livewire;
    
    use Livewire\Component;
    
    class YourComponent extends Component
    {
        public $name = 'World';
    
        public function render()
        {
            return view('livewire.your-component');
        }
    }
    
  4. Create the Blade View At wp-content/themes/your-theme/resources/views/livewire/your-component.blade.php:

    <input wire:model="name" type="text">
    <p>Hello, {{ $name }}!</p>
    
  5. Use the Component in WordPress In a template file (e.g., page-template.php):

    <?php
    use App\Livewire\YourComponent;
    ?>
    <livewire your-component />
    

First Use Case: Dynamic Form Handling

Replace a traditional WordPress form with Livewire for real-time validation and submission:

// app/Livewire/ContactForm.php
public $email;
public $message;
protected $rules = [
    'email' => 'required|email',
    'message' => 'required|min:10',
];

public function submit()
{
    // Process form (e.g., save to DB or send email)
    $this->reset('message'); // Clear message after submission
}

View (livewire/contact-form.blade.php):

<form wire:submit.prevent="submit">
    <input wire:model="email" type="email" placeholder="Email">
    <textarea wire:model="message" placeholder="Message"></textarea>
    <button type="submit">Send</button>
    @error('email') <span>{{ $message }}</span> @enderror
</form>

Implementation Patterns

1. Component Organization

  • Namespace Structure: Follow App\Livewire\Domain\Feature\Component (e.g., App\Livewire\Ecommerce\Cart\CartComponent).
  • View Location: Store Blade views in resources/views/livewire/domain/feature/component.blade.php.
  • Reusable Components: Extend base components for shared logic (e.g., BaseFormComponent).

2. Integration with WordPress

  • Shortcodes:
    add_shortcode('dynamic_content', function() {
        return '<livewire dynamic-content-component />';
    });
    
  • REST API + Livewire: Fetch WordPress REST data in mount() and update Livewire state:
    public function mount()
    {
        $this->posts = \WP_Query::newInstance()->posts;
    }
    

3. State Management

  • Persistent State: Use sessionStorage for data that should persist across page reloads:
    public $persistentValue;
    
    public function mount()
    {
        $this->persistentValue = sessionStorage()->get('key', 'default');
    }
    
    public function save()
    {
        sessionStorage()->put('key', $this->persistentValue);
    }
    
  • WordPress Transients: Store Livewire state in WordPress transients for caching:
    public function mount()
    {
        $this->data = get_transient('livewire_cache_key');
    }
    
    public function updatedData()
    {
        set_transient('livewire_cache_key', $this->data, HOUR_IN_SECONDS);
    }
    

4. Workflow: CRUD Operations

  • Example: Post Editor
    // app/Livewire/PostEditor.php
    public $title;
    public $content;
    public $postId;
    
    public function mount($postId = null)
    {
        if ($postId) {
            $post = get_post($postId);
            $this->title = $post->post_title;
            $this->content = $post->post_content;
        }
    }
    
    public function save()
    {
        wp_update_post([
            'ID' => $this->postId ?? wp_insert_post([
                'post_title' => $this->title,
                'post_content' => $this->content,
                'post_status' => 'draft',
            ]),
            'post_title' => $this->title,
            'post_content' => $this->content,
        ]);
    }
    

5. Event Handling

  • WordPress Actions/Filters:
    public function mount()
    {
        add_action('wp_loaded', [$this, 'handleWpEvent']);
    }
    
    public function handleWpEvent()
    {
        // Logic tied to WordPress lifecycle
    }
    
  • Custom Livewire Events:
    // Emit from component
    $this->emit('customEvent', ['data' => 'value']);
    
    // Listen in another component
    protected $listeners = ['customEvent' => 'handleEvent'];
    

6. Asset Management

  • Custom CSS/JS: Load assets via wp_enqueue_script in mount():
    public function mount()
    {
        wp_enqueue_script('custom-script', get_template_directory_uri() . '/js/custom.js');
    }
    

Gotchas and Tips

Pitfalls

  1. WordPress Nonce Validation

    • Livewire’s built-in CSRF protection may conflict with WordPress nonces. Exclude Livewire routes from WordPress nonce checks:
      add_filter('wp_starter_livewire_excluded_routes', function($routes) {
          return array_merge($routes, [
              'livewire/update',
              'livewire/lock',
          ]);
      });
      
  2. Plugin/Theme Conflicts

    • Some WordPress plugins (e.g., caching, security) may interfere with Livewire’s AJAX requests. Test with:
      • Query Monitor to debug HTTP requests.
      • Disable plugins to isolate conflicts.
  3. State Persistence

    • Avoid storing large data in Livewire state. Use WordPress transients or the database for heavy data.
  4. Blade vs. WordPress Template Tags

    • WordPress template tags (e.g., the_title(), get_header()) won’t work in Livewire Blade views. Use PHP directly or fetch data via WordPress APIs in the component class.
  5. Livewire + Gutenberg

    • Livewire components cannot be used directly in Gutenberg blocks. Use a custom block with @php tags to embed Livewire:
      // Example: my-block.js
      const el = wp.element.createElement;
      const MyBlock = () => {
          return el('div', { className: 'my-block' }, [
              el('div', { dangerouslySetInnerHTML: { __html: '<livewire dynamic-content />' } }),
          ]);
      };
      

Debugging

  1. Livewire Logs Enable Livewire logging in wp-config.php:

    define('WPSTARTER_LIVEWIRE_LOG', true);
    

    Logs appear in /wp-content/debug/livewire.log.

  2. Network Tab

    • Check the Network tab in DevTools for failed Livewire requests (look for /livewire/update).
    • Common issues:
      • 403 Forbidden: Missing CSRF token or WordPress nonce.
      • 500 Internal Server Error: PHP errors in component logic.
  3. XHR Payloads Inspect Livewire’s XHR payloads to verify state updates:

    {
        "component": "your-component",
        "data": {
            "name": "New Value"
        }
    }
    

Tips

  1. Hybrid Components Combine Livewire with WordPress widgets:

    // app/Livewire/WidgetComponent.php
    public function mount()
    {
        register_widget([$this, 'widget']);
    }
    
    public function widget($args)
    {
        return '<livewire widget-component />';
    }
    
  2. Performance

    • Lazy Load Components: Use wire:ignore for non-interactive elements.
    • Debounce Inputs: Add wire:debounce.500ms to inputs to reduce server load:
      <input wire:model.debounce.500ms="searchQuery">
      
  3. Testing

    • Use wpstarter/livewire-testing for PHPUnit tests:
      use Livewire\Testing\TestableLivewire;
      
      public function test_component()
      {
          $component = TestableLivewire::render(YourComponent::class);
          $component->set('name', 'Test');
      
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours