How to use Select 2 with multiple options in Laravel and Livewire
Tags: laravel, beginners, codenewbie, programming
Published: 2021-09-13 18:07:34

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.

```php
<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>
```

3 - Now create a livewire component by using command
```php
php artisan make:livewire Select2Example
```
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.
```php
window.$ = window.jQuery = require("jquery");
window.select2 = require("select2");
```

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
```php 
public $languages = [
        'Python',
        'Php',
        'Java',
        'C',
        'C++',
];
```
also create two public variable
```php
public $prog_lang = '';
public $programming_languages = [];
```

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.

```php
    public function hydrate()
    {
        $this->emit('select2');
    }
```
Here is the full code
```php
<?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');
    }
}
```
6 - now open select2-example.blade.php file add below code
```php
<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
```

In this way we can use select2 in laravel and livewire application. 
Thank you for reading :lion: :unicorn: