Select2 Multiple select using Livewire

Livewire

Demo

Selected Tasks : None

This is a free component. Login to your account to view / download the component code.

Component Class


<?php

namespace App\Http\Livewire;

use App\Models\DummyTask;
use Livewire\Component;

class Select2Multiple extends Component
{
    public $tasks = [];
    public $selectedTasks = [];

    public function render()
    {
        return view('livewire.select2-multiple');
    }

    public function mount(){
        $this->tasks = DummyTask::all();
    }
}


Component View File


<div>
    <div wire:ignore>
        <label for="taskSelect" class="form-label">Select Tasks</label>
        <select class="form-select" id="taskSelect" multiple="multiple" >
            @foreach($tasks as $task)
                <option id="{{$task->id}}">{{$task->title}}</option>
            @endforeach
        </select>
    </div>
    <div class="my-3">
        Selected Tasks : 
        @forelse($selectedTasks as $task)
            {{$task}},
        @empty
            None
        @endforelse
    </div>
    <script>
        $(document).ready(function() {
            $('#taskSelect').select2();

            $('#taskSelect').on('change', function (e) {
                @this.set('selectedTasks', $(this).val());
            });
        });
    </script>
</div>

Usage


    @livewire('select2-multiple')  

Documentation

To use select2 plugin, make sure you include its CSS and JS library in your project.


    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js" defer></script>   </script>

The javascript code is straighftforward. We initialize select2 box on the taskSelect input, and on the change event we call the set event of livewire which sets the desired input field with the value of select2 box.

Make sure you mark you select box with wire:ignore directive, this will make sure livewire does not repaints the input on reload, since we don't want to loose select2 classes and selected values.

Download Code

Download the Component class, view file and other required files

Please login to download the component code