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 Forms Laravel Package

aerni/livewire-forms

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Installation

    composer require aerni/livewire-forms
    php artisan vendor:publish --tag=livewire-forms-config
    

    Publish the config to customize default settings (e.g., reCAPTCHA keys, form view paths).

  2. Create a Statamic Form Define a form in Statamic (e.g., contact form) with a blueprint. Example fields:

    fields:
      name:
        type: text
        validate: required|min:3
      email:
        type: email
        validate: required|email
    
  3. Generate a Livewire Component Use Artisan to scaffold a Livewire component tied to your form:

    php artisan make:livewire ContactForm
    
  4. Integrate the Form in a Blade View

    <livewire:contact-form form="contact" />
    

    The form prop maps to your Statamic form handle.

  5. Test Real-Time Validation Submit the form without JavaScript—Livewire handles validation server-side. Observe real-time feedback as users type.


First Use Case: Simple Contact Form

  • Goal: Replace a traditional AJAX-submitted contact form with Livewire.
  • Steps:
    1. Create a Statamic form blueprint (contact.yml) with fields for name, email, and message.
    2. Generate a Livewire component (php artisan make:livewire ContactForm).
    3. Extend the component to handle submission:
      public function submit()
      {
          $this->validate();
          // Process submission (e.g., send email, save to DB)
          session()->flash('success', 'Form submitted!');
          $this->reset();
      }
      
    4. Use the component in a Blade template:
      <livewire:contact-form form="contact" />
      
  • Outcome: A form with real-time validation, no client-side JS libraries, and seamless Statamic integration.

Implementation Patterns

Core Workflows

1. Blueprint-Driven Form Building

  • Pattern: Use Statamic form blueprints as the single source of truth for form structure, validation, and display logic.
  • Example:
    # contact.yml
    fields:
      name:
        type: text
        validate: required|min:3
        display: "Full Name"
        instructions: "Your legal name"
      terms:
        type: checkbox
        validate: accepted
        display: "I agree to the terms"
    
  • Livewire Integration: The package auto-generates form fields, labels, and validation rules from the blueprint. Override defaults in the Livewire component:
    public $form = 'contact';
    
    public function mount()
    {
        $this->fields = collect($this->formBlueprint()->fields)->mapWithKeys(function ($field) {
            return [$field['handle'] => $field];
        });
    }
    

2. Real-Time Validation

  • Pattern: Leverage Livewire’s reactivity to validate fields as users type.
  • Implementation:
    • Use wire:model.lazy for fields to trigger validation on blur:
      <input wire:model.lazy="name" type="text">
      @error('name') <span>{{ $message }}</span> @enderror
      
    • Customize validation messages in the blueprint or component:
      public function rules()
      {
          return [
              'name' => ['required', 'min:3'],
              'email' => ['required', 'email'],
          ];
      }
      

3. Dynamic Display Conditions

  • Pattern: Show/hide fields based on blueprint conditions (e.g., conditional logic).
  • Example Blueprint:
    fields:
      plan:
        type: select
        options:
          basic: Basic Plan
          pro: Pro Plan
        display: "Select Plan"
      pro_features:
        type: checkboxes
        options:
          feature1: Feature 1
          feature2: Feature 2
        display: "Pro Features"
        conditions:
          plan: pro
    
  • Livewire Handling: The package automatically applies conditions. Extend in the component:
    public function updatedPlan($value)
    {
        $this->dispatchBrowserEvent('refresh-form');
    }
    

4. Multi-Site and Localization

  • Pattern: Translate form labels, placeholders, and instructions for multi-site Statamic setups.
  • Implementation:
    • Use Statamic’s localization features in blueprints:
      display: "Name ({{ __('lang.key') }})"
      
    • Access translations in Livewire:
      public function getDisplayLabelAttribute($field)
      {
          return __($this->fields[$field]['display'] ?? '');
      }
      

5. Spam Protection

  • Pattern: Integrate honeypot or reCAPTCHA v2 without client-side JS.
  • Config:
    // config/livewire-forms.php
    'spam_protection' => [
        'driver' => 'honeypot',
        // or 'recaptcha' with keys
    ],
    
  • Livewire Component:
    public function submit()
    {
        $this->validate([
            'honeypot' => 'required|honey:field',
        ]);
        // Proceed with submission
    }
    

Integration Tips

1. Customizing Form Views

  • Override the default form view (resources/views/vendor/livewire-forms/form.blade.php) by publishing the views:
    php artisan vendor:publish --tag=livewire-forms-views
    
  • Extend the published view to add custom HTML or Alpine.js interactions.

2. Handling File Uploads

  • Use Statamic’s file upload fields in blueprints:
    fields:
      avatar:
        type: upload
        validate: max:1024
    
  • Process uploads in Livewire:
    public function submit()
    {
        $this->validate();
        $file = $this->avatar;
        $path = $file->store('avatars');
        // Save path to DB
    }
    

3. Styling with Tailwind/Alpine

  • Add Alpine.js to toggle field visibility dynamically:
    <div x-data="{ showProFeatures: false }">
        <input wire:model="plan" @change="showProFeatures = ($event.target.value === 'pro')">
        <div x-show="showProFeatures">
            <livewire:pro-features-form />
        </div>
    </div>
    

4. Extending Validation

  • Add custom validation rules to the component:
    protected function rules()
    {
        return [
            'age' => ['required', 'integer', 'min:18'],
            'custom_rule' => ['custom_rule:param'],
        ];
    }
    
  • Register custom rules in AppServiceProvider:
    Validator::extend('custom_rule', function ($attribute, $value, $parameters) {
        return $value === $parameters[0];
    });
    

5. Form Submission Handlers

  • Use Livewire’s afterSubmitting hook to log submissions or trigger events:
    protected function afterSubmitting()
    {
        event(new FormSubmitted($this->formData));
        return redirect()->route('thank-you');
    }
    

Gotchas and Tips

Pitfalls

1. Blueprint Cache Invalidation

  • Issue: Changes to form blueprints may not reflect in Livewire due to caching.
  • Fix: Clear Statamic’s cache:
    php artisan statamic:clear-cached-data
    
  • Tip: Use php artisan livewire:discover to refresh Livewire components.

2. Real-Time Validation Performance

  • Issue: Heavy validation rules (e.g., complex regex) can cause lag.
  • Fix: Use wire:model.debounce.500ms to delay validation:
    <input wire:model.debounce.500ms="email">
    

3. Multi-Site Field Handling

  • Issue: Fields may not respect site-specific translations or conditions.
  • Fix: Explicitly set the site in the component:
    public function mount()
    {
        $this->site = Statamic::sites()->current();
    }
    

4. Livewire Component Naming Conflicts

  • Issue: Naming a Livewire component the same as a Statamic form handle can cause confusion.
  • Fix: Use a unique component name (e.g., ContactForm for contact form).

5. reCAPTCHA Integration

  • Issue: reCAPTCHA may fail silently if keys are misconfigured.
  • Debug: Check
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.
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
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai