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

Choices Laravel Package

contao-components/choices

Contao Components Choices adds the Choices.js library integration for Contao CMS, enhancing select boxes and input fields with searchable, taggable, and multi-select UI features. Ideal for modern form UX with minimal setup.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require contao-components/choices
    

    Publish the assets (if needed):

    php artisan vendor:publish --provider="ContaoComponents\Choices\ChoicesServiceProvider" --tag=public
    
  2. Basic Usage Include the Choices.js bundle in your Blade template:

    @choicesJs
    

    Initialize Choices on an element:

    const choices = new Choices('#my-select-element', {
        removeItemButton: true,
        placeholder: true,
        placeholderValue: 'Select an option...',
    });
    
  3. First Use Case Replace a standard <select> with a searchable, multi-select dropdown:

    <select name="tags" multiple>
        <option value="1">Option 1</option>
        <option value="2">Option 2</option>
    </select>
    

    Initialize with:

    new Choices('#tags', { removeItemButton: true });
    

Implementation Patterns

Common Workflows

  1. Dynamic Initialization Use Laravel’s Blade directives or Alpine.js to initialize Choices conditionally:

    <select x-data="{ choices: null }" x-init="choices = new Choices($refs.select)">
        @foreach($options as $option)
            <option value="{{ $option->id }}">{{ $option->name }}</option>
        @endforeach
    </select>
    
  2. Integration with Forms Bind Choices to Laravel Form requests:

    public function store(Request $request) {
        $validated = $request->validate([
            'tags' => 'required|array',
            'tags.*' => 'exists:tags,id',
        ]);
        // Process $validated['tags'] (array of selected IDs)
    }
    
  3. Reactive Updates Update Choices dynamically via AJAX:

    fetch('/api/search')
        .then(response => response.json())
        .then(data => {
            choices.setChoices(data.map(item => ({ value: item.id, label: item.name })));
        });
    
  4. Laravel Collections Integration Convert a Laravel Collection to Choices-compatible format:

    $options = $items->map(fn ($item) => [
        'value' => $item->id,
        'label' => $item->name,
        'disabled' => $item->is_disabled,
    ]);
    

Integration Tips

  • Asset Optimization: Use Laravel Mix/Vite to bundle Choices.js with your app.
  • Localization: Pass translations via Laravel’s __() helper:
    new Choices('#select', {
        searchPlaceholderValue: '@lang("Select an option...")',
    });
    
  • Server-Side Rendering: For SSR (e.g., Inertia.js), initialize Choices only on the client:
    if (typeof window !== 'undefined') {
        new Choices('#select');
    }
    

Gotchas and Tips

Pitfalls

  1. Duplicate Initialization Avoid re-initializing Choices on the same element. Store instances in a global object:

    window.choicesInstances = window.choicesInstances || {};
    window.choicesInstances.mySelect = new Choices('#my-select');
    
  2. Memory Leaks Destroy instances when no longer needed (e.g., on tab/unmount):

    choices.destroy();
    
  3. Laravel Mix/Vite Conflicts Ensure Choices.js is not bundled twice. Exclude it from auto-imports if using Vite:

    // vite.config.js
    optimizeDeps: { exclude: ['choices.js'] },
    
  4. CSRF Token Mismatch When submitting forms with Choices, ensure the CSRF token is included:

    <input type="hidden" name="_token" value="{{ csrf_token() }}">
    

Debugging

  • Console Errors: Check browser console for Choices is not defined (missing @choicesJs directive).
  • Invalid Options: Validate options structure (must include value and label).
  • Event Listeners: Use choices.on('change') to debug dynamic updates:
    choices.on('change', (event) => {
        console.log('Selected:', event.detail.selected);
    });
    

Extension Points

  1. Custom Templates Override Choices templates via CSS classes or inline styles:

    new Choices('#select', {
        classNames: {
            containerOuter: 'my-custom-container',
        },
    });
    
  2. Laravel Service Provider Extend the package’s default config:

    // config/choices.php
    'default_options' => [
        'searchEnabled' => true,
        'shouldSortItems' => false,
    ],
    
  3. Alpine.js Integration Use Alpine’s x-model to sync Choices with Laravel models:

    <select x-model="form.tags" x-init="new Choices($refs.select)">
        @foreach($tags as $tag)
            <option value="{{ $tag->id }}">{{ $tag->name }}</option>
        @endforeach
    </select>
    
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor