DEV Community

Cover image for How to use Select 2 with multiple options in Laravel and Livewire
Snehal Rajeev Moon
Snehal Rajeev Moon

Posted on

How to use Select 2 with multiple options in Laravel and Livewire

Hello, In this blog post we are going to see how we can use select 2 in laravel and livewire application.
I am going to describe it with multiple select example to select multiple languages.

1- First you need to install laravel and livewire (I am not going to describe installation steps it here).

2 - The next step is to add following links and script to your app.blade.php layout file.

<script src="{{ asset('js/app.js') }}" defer></script>
<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"></script>
Enter fullscreen mode Exit fullscreen mode

3 - Now create a livewire component by using command

php artisan make:livewire Select2Example
Enter fullscreen mode Exit fullscreen mode

It will create two files within its respective folder

  • Select2Example.php (App\Http\Livewire\Select2Example.php)
  • select2-example.blade.php (resoureces\views\livewire\select2-example.blade.php)

4 - Now we have to register it in app.js file, add below given code.

window.$ = window.jQuery = require("jquery");
window.select2 = require("select2");
Enter fullscreen mode Exit fullscreen mode

5 - After that open Select2Example controller in which you will see render method which returns the livewire select2-example blade file.
Now we need to add list of languages by defining language array

public $languages = [
        'Python',
        'Php',
        'Java',
        'C',
        'C++',
];
Enter fullscreen mode Exit fullscreen mode

also create two public variable

public $prog_lang = '';
public $programming_languages = [];
Enter fullscreen mode Exit fullscreen mode

Now create a hydrate lifecycle of livewire into the controller in some cases we require it and emit select2 for more clarity let see the below code.

    public function hydrate()
    {
        $this->emit('select2');
    }
Enter fullscreen mode Exit fullscreen mode

Here is the full code

<?php

namespace App\Http\Livewire;

use Livewire\Component;

class Select2Example extends Component
{
    public $prog_lang = '';
    public $programming_languages = [];

    public $languages = [
        'Python',
        'Php',
        'Java',
        'C',
        'C++',
    ];

    // lifecycle hook sometimes we require it for select2
    public function hydrate()
    {
        $this->emit('select2');
    }
    public function render()
    {
        return view('livewire.select2-example')->extends('layouts.app');
    }
}
Enter fullscreen mode Exit fullscreen mode

6 - now open select2-example.blade.php file add below code

<div>
    <div wire:ignore>
        <div class="mt-5 relative" wire:ignore>
            <select id="select2-dropdown" name="programming_languages[]" multiple
                class="appearance-none h-full rounded-r border-t border-r border-b block appearance-none w-full bg-white border-gray-300 text-gray-700 py-2 px-4 pr-8 leading-tight focus:placeholder-gray-600 focus:text-gray-700 focus:outline-none">
                <option value="" disabled="disabled">Select Option</option>
                @foreach($languages as $language)
                    <option value="{{ $language }}">{{ $language }}</option>
                @endforeach
            </select>
            <div x-data="{can:@entangle('prog_lang')}" x-bind:class="can.length > 0 ? 'hidden': 'absolute top-2 right-1'" >
                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                    <path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" />
                </svg>
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script>
    $(document).ready(function () {
        $('#select2-dropdown').select2({
            placeholder: "select languages",
            multiple: true,
            allowClear: true,
        });
        $('#select2-dropdown').on('change', function (e) {
            var data = $('#select2-dropdown').select2("val");
            let closeButton = $('.select2-selection__clear')[0];
            if(typeof(closeButton)!='undefined'){
                if(data.length<=0)
                {
                    $('.select2-selection__clear')[0].children[0].innerHTML = '';
                } else{
                    $('.select2-selection__clear')[0].children[0].innerHTML = 'x';
                }
            }
            @this.set('prog_lang', data);
        });
    });

</script>
@endpush
Enter fullscreen mode Exit fullscreen mode

In this way we can use select2 in laravel and livewire application.
Thank you for reading 🦁 🦄

Top comments (2)

Collapse
 
vitoo profile image
Victorien Plancke

Thanks it helped me ! :)

Collapse
 
snehalkadwe profile image
Snehal Rajeev Moon

Thank you !! 😊