09-03-2022

Livewire with Select2

When you use Livewire, it could be tricky, to use jquery plugins. But hey, here is a short trick, how to use Select2 with Livewire.

First of all, you have to add the following part in your layout, after @livewireScripts.

@livewireScripts
<!-- This should be added after the livewire scripts part -->
@stack('scripts-child')

With the help of this, you can push javascript snippets to the right place. At your component you have a select input, similar to the following:

<div wire:ignore class=""> 
  <label class="" for="productSearch">Place Product name:</label> 
  <select class="select2 productSearchClass" name="productSearch" id="productSearch"> 
  <option value="" selected>Select</option> 
  @foreach($searchForProducts as $searchForProduct) 
    <option value="{{$searchForProduct->id}}"> 
      {{$searchForProduct->name}} 
    </option> 
  @endforeach 
  </select> 
</div>

The most important part is, the wire:ignore at the main div.

Now at the end of the livewire component, you should have the following snippet:

@push('scripts-child')
<script> 
  $(document).ready(function() { 
    $('.productSearchClass').select2(); 
    $('.productSearchClass').on('change', function (e) { 
      @this.set('productSearch', e.target.value);
    });
  });
</script>
@endpush

The snippet above is easy.

  • It adds select2 style and functions to the productSearch class.
  • Whenever it changes, a set method will transfer it's value to te productSearch Livewire public attribute.

That's all! Have a nice day!

© 2022 PappZ. All rights reserved.