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

pharaonic/livewire-select2

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require pharaonic/livewire-select2
    

    Publish the config (optional):

    php artisan vendor:publish --provider="Pharaonic\LivewireSelect2\ServiceProvider"
    
  2. Basic Usage:

    use Pharaonic\LivewireSelect2\LivewireSelect2;
    
    public function mount()
    {
        $this->options = [
            'id' => 'my-select',
            'label' => 'Choose an option',
            'options' => [
                ['id' => 1, 'text' => 'Option 1'],
                ['id' => 2, 'text' => 'Option 2'],
            ],
        ];
    }
    
    public function render()
    {
        return LivewireSelect2::make('options');
    }
    
  3. Blade Integration:

    @livewireSelect2('options', 'my-component')
    

First Use Case

Replace a standard <select> dropdown with a Searchable, Taggable, and Customizable Select2 component in a Livewire form. Ideal for:

  • User role assignment
  • Multi-select categories
  • Dynamic data fetching (e.g., autocomplete for products).

Implementation Patterns

Core Workflows

  1. Dynamic Data Binding:

    // Fetch data from DB and bind to Select2
    public function mount()
    {
        $this->users = User::all()->pluck('name', 'id');
        $this->options = [
            'label' => 'Select User',
            'options' => $this->users,
            'wire:model' => 'selectedUserId',
        ];
    }
    
  2. Multi-Select with Tags:

    $this->options = [
        'label' => 'Select Tags',
        'options' => Tag::all()->pluck('name', 'id'),
        'multiple' => true,
        'tags' => true, // Enable tagging new options
    ];
    
  3. Remote Data Fetching:

    // Use `wire:model.live` for debounced search
    $this->options = [
        'label' => 'Search Products',
        'url' => route('api.products.search'),
        'minimumInputLength' => 2,
        'placeholder' => 'Type to search...',
    ];
    

Integration Tips

  • Livewire Rules: Combine with Laravel Validation:
    protected $rules = ['selectedUserId' => 'required|exists:users,id'];
    
  • Custom Styling: Override Select2 CSS via published config:
    /* resources/css/select2-custom.css */
    .select2-container--default .select2-selection--single {
        border: 1px solid #ccc;
    }
    
  • Event Handling: Listen to select2:select or select2:unselect:
    public function updatedSelectedUserId($value)
    {
        $this->emit('userSelected', $value);
    }
    

Gotchas and Tips

Pitfalls

  1. JavaScript Conflicts:

    • Ensure Select2 JS is loaded after Livewire’s Alpine.js.
    • If using multiple Select2 instances, wrap in unique IDs:
      $this->options['id'] = 'unique-select-' . uniqid();
      
  2. AJAX Caching:

    • Remote data (url) may cache responses. Use cache: false in config or append a timestamp:
      $this->options['url'] = route('api.products.search') . '?t=' . time();
      
  3. Livewire Model Binding:

    • For multi-select, ensure wire:model is an array:
      public $selectedTags = [];
      $this->options['wire:model'] = 'selectedTags';
      

Debugging

  • Check Console: Look for Uncaught ReferenceError if Select2 JS fails to load.
  • Inspect Network Tab: Verify AJAX requests for remote data.
  • Clear Config Cache:
    php artisan config:clear
    

Extension Points

  1. Custom Templates: Override Select2 templates via config:

    'templates' => [
        'result' => '<div class="custom-result">{{ $data.text }}</div>',
    ],
    
  2. Event Extensions: Extend core events (e.g., select2:initialized) via Livewire hooks:

    protected $listeners = ['select2:initialized' => 'handleSelect2Init'];
    
    public function handleSelect2Init()
    {
        $this->dispatch('select2Ready');
    }
    
  3. Server-Side Processing: Use ajax config for complex queries:

    $this->options['ajax'] = [
        'url' => route('api.users.search'),
        'dataType' => 'json',
        'delay' => 250,
        'data' => function($params) {
            return ['q' => $params['term']];
        },
        'processResults' => function($data) {
            return [
                'results' => array_map(fn($user) => [
                    'id' => $user['id'],
                    'text' => $user['name'],
                ], $data['users']),
            ];
        },
    ];
    
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