<!DOCTYPE html><html><body><p># Livewire Select2 documentation (v1.x) &gt; Canonical: https://pharaonic.dev/packages/livewire/select2/1.x &gt; Version: v1.x (latest release 1.4.0, 2026-12-02) &gt; Install: composer require pharaonic/livewire-select2 &gt; Repository: https://github.com/Pharaonic/livewire-select2 &gt; All versions: https://pharaonic.dev/packages/livewire/select2/4.x.md https://pharaonic.dev/packages/livewire/select2/3.x.md https://pharaonic.dev/packages/livewire/select2/2.x.md https://pharaonic.dev/packages/livewire/select2/1.x.md :::badges - Livewire Package {color=blue} - v1.4.0 {color=green} - MIT License {color=purple} ::: # Livewire Select2 Livewire Select2 turns a `<select>` in a Livewire component into a Select2 widget that stays in sync with the component. Put `data-pharaonic="select2"` and `wire:model` on the select, load one Blade directive, and the widget follows the property in both directions: what the user picks reaches the component, and what the server sets shows in the widget. It is built on Livewire Assistant, which finds the elements, binds each one to the component that owns it, and cleans them up when Livewire removes them. :::features ### Two-way binding User choices update the property, and values the server sets update the widget, without echo requests. ### Native wire:model Use wire:model with its usual modifiers, or data-property, on single and multiple selects and dot paths. ### Dynamic and dependent selects Selects that Livewire adds, removes, or re-renders with new options are mounted, cleaned up, or rebuilt for you. ### Right component, always Each select binds to the component around it, so nested components and many selects per page just work. ### Images and templates Show an image beside each option without JavaScript, or name a template function once and reuse it. ### No Node build required The script ships prebuilt in the Composer package, or as an ES module for bundlers such as Vite. ::: :::info Livewire 1 line This documentation covers the 1.x line, which supports Livewire 1. Each Livewire major gets its own line. ::: ## Installation Install the package with Composer, keep jQuery and Select2 on the page, and load the scripts once. ### Requirements - PHP 7.4 (Livewire 1 only installs on PHP 7) - Laravel 7.30+ or 8.75+ - Livewire 1.3.0 to 1.3.9, except 1.3.7 (see [Compatibility](#compatibility)) - jQuery and Select2 4, loaded by your application - A modern browser (ES2019); Internet Explorer is not supported ### Composer Installation ```bash title="Terminal" no-line-numbers composer require pharaonic/livewire-select2 ``` Composer also installs `pharaonic/livewire-assistant`. Laravel discovers both service providers automatically. There is nothing to publish and no configuration file. To change the package's error messages, publish its English and Arabic translations with `php artisan vendor:publish --tag=select2-translations`. :::warning Composer and unmaintained releases Every Livewire 1 release, and every Laravel 7 and 8 release, has security advisories that no release in its major fixes. Recent Composer versions refuse to install or update them until you allow them. If you accept the risk, allow them in your application's `composer.json`: ```bash title="Terminal" no-line-numbers composer config --json policy.advisories.ignore '{"livewire/livewire": "No fixed release within Livewire 1.", "laravel/framework": "No fixed release within this Laravel major.", "league/commonmark": "No fixed release within this Laravel major.", "league/flysystem": "No fixed release within this Laravel major."}' ``` Read [Compatibility](#compatibility) before accepting the risk. ::: ### Load the Scripts Load jQuery and Select2 the way you already do, then add `@livewireSelect2Scripts` to your layout. It can go before or after `@livewireScripts`. ```blade title="resources/views/layouts/app.blade.php" <meta charset="utf-8"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css"><script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script><script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script> @livewireStyles @yield('content') @livewireScripts @livewireSelect2Scripts ``` The directive renders two `<script>` tags:the Livewire Assistant runtime and this integration.Each is rendered once per page,even when layouts,partials,and `@livewireAssistantScripts` ask for it again.```html no-copy<script src="https://example.com/pharaonic/livewire-assistant/assistant.js?id=3f9a1c2b7d4e5f60"data-turbolinks-eval="false"></script><script src="https://example.com/pharaonic/livewire-select2/select2.js?id=0d8eee40cb71f6d7" data-turbolinks-eval="false"></script> ``` jQuery and Select2 are read from `window.jQuery` when a select mounts, not when the script loads, so their order relative to the directive does not matter. If they are still missing when the page has finished loading, the select is reported as `mount-failed` with the `select2-missing` cause. ### Vite and Other Bundlers When jQuery and Select2 come from npm, expose jQuery on `window` and attach Select2 to that same jQuery. The package never uses `$`, so you do not need a global `$`. ```js title="resources/js/app.js" import jQuery from 'jquery' import select2 from 'select2' window.jQuery = jQuery select2() ``` Keep `@livewireSelect2Scripts` in the layout, or import the ES modules instead (see below). ### Content Security Policy Pass a nonce when your CSP uses one. Both tags get it, escaped. ```blade title="resources/views/layouts/app.blade.php" @livewireSelect2Scripts(['nonce' =&gt; $cspNonce]) ``` `nonce` is the only option. An unknown option or a non-string nonce throws an `InvalidArgumentException` while the view renders. The scripts never use `eval` or inline code. ### How the Script Is Served | Route | Name | | --- | --- | | `GET /pharaonic/livewire-select2/select2.js` | `pharaonic.livewire-select2.script` | The route serves `dist/livewire-select2.js` from the installed package, without session or cookies. The `id` query value is a hash of the file: a matching `id` is cached for a year, anything else is served with `no-cache`. After `composer update` the hash changes, so browsers fetch the new script on the next page load. Nothing needs publishing, and the route works with `php artisan route:cache`. ### ES Module If you bundle your JavaScript, import the ES modules from the Composer packages instead of using the directive. Import the Assistant too: the integration registers with it but never loads it. ```js title="resources/js/app.js" import jQuery from 'jquery' import select2 from 'select2' import '../../vendor/pharaonic/livewire-assistant/dist/livewire-assistant.esm.js' import { define } from '../../vendor/pharaonic/livewire-select2/dist/livewire-select2.esm.js' window.jQuery = jQuery select2() ``` The ES module and the browser build share one integration per page, so loading both is harmless. :::success Installation Complete Mark a select with `data-pharaonic="select2"` and you are done. See [Basic Usage](#basic-usage). ::: ## Basic Usage A Select2 field is a normal `<select>` with `data-pharaonic="select2"` and `wire:model`, wrapped in `wire:ignore`. ### The Component ```php title="app/Http/Livewire/Profile.php" <?php namespace App\Http\Livewire; use Illuminate\Contracts\View\View; use Livewire\Component; class Profile extends Component { public $country = '2'; public array $languages = ['ar']; public function render(): View { return view('livewire.profile'); } } ``` ### The View ```blade title="resources/views/livewire/profile.blade.php" <div><div wire:ignore><select data-pharaonic="select2" wire:model="country" data-placeholder="Choose a country" data-clear><option value=""></option><option value="1">Egypt</option><option value="2">Jordan</option></select></div><div wire:ignore><select multiple data-pharaonic="select2" wire:model="languages"><option value="ar">Arabic</option><option value="en">English</option></select></div> ``` ### The Route ```php title="routes/web.php" Route::livewire('/profile', 'profile'); ``` Livewire 1 renders the component inside `@yield('content')` of `layouts.app`, the layout from [Installation](#installation). That is all. The first select shows Jordan; picking Egypt sets `$country` to `"1"`; `$this-&gt;country = '2'` on the server selects Jordan again. The second select holds an array. ### Why wire:ignore Livewire updates a component's HTML after each request to match the server. Select2 hides the `<select>` and adds its own markup next to it, which that update would remove. `wire:ignore` tells Livewire to leave the block alone, so the widget survives every request. The package keeps the value in sync through the component, not through the HTML. A select can also live outside `wire:ignore`. The package then rebuilds the widget after each Livewire update, which is useful when the server changes its options. See [Dynamic Selects](#dynamic-selects). ### The Attributes | Attribute | Purpose | | --- | --- | | `data-pharaonic="select2"` | Marks the element; required | | `wire:model="property"` | The property to bind, with its modifiers | | `data-property="property"` | The property to bind, when you do not use `wire:model` | | `data-tags`, `data-clear`, `data-search-off`, `data-parent` | Shorthands for common Select2 options (see [Options](#options)) | | `data-placeholder` and other Select2 `data-*` attributes | Read by Select2 itself | | `data-options='{...}'` | A JSON object passed to Select2, for everything else | | `data-component-id` | Optional: bind to a specific component instead of the one around the select | Without `wire:model` or `data-property`, the select becomes a Select2 widget that is not bound to anything. :::tip Placeholders need an empty option Select2 shows the placeholder of a single select only when it has an empty `<option value="">`. Put one first. ::: ### Labels and Validation Messages Livewire never updates anything inside `wire:ignore`, including an `@error` message placed there. Keep labels and messages outside the ignored block, so they update with the component: ```blade <label for="country">Country</label><div wire:ignore><select id="country" data-pharaonic="select2" wire:model="country">...</select></div> @error('country') <span class="text-danger">{{ $message }}</span> @enderror ``` ## Binding The package binds a select to one component property, in both directions. ### wire:model or data-property The property comes from `wire:model` on the select, or from `data-property`. When both are present, `data-property` wins. ```blade <select data-pharaonic="select2" wire:model="country">...</select><select data-pharaonic="select2" data-property="address.country_id">...</select> ``` Both accept a property name or a dot path (`address.city`, `rows.2.product`). ### Modifiers on Livewire 1 Livewire 1 has no deferred updates, so every write is sent right away. `wire:model.lazy` and `wire:model.debounce.500ms` are accepted and behave like `wire:model`: a Select2 choice is a single change, so there is nothing to debounce. ### How Values Move - **Initial value.** When the select mounts, it shows the property's current value. - **User to server.** A Select2 change sends the new value to the property in a Livewire request. - **Server to widget.** When a Livewire update changes the property, from an action, a lifecycle hook, or another field, the widget selects the new value. - **No echo.** Values the server sets are shown without being sent back, and a choice equal to the current value sends nothing. ### Value Types Select2 works with strings. The package converts at the boundary: | Property value | Single select shows | Multiple select shows | | --- | --- | --- | | `null` | the empty option | nothing | | `''` | the empty option | nothing | | `0` or `'0'` | the option with value `0` | | | `2` or `'2'` | the option with value `2` | | | `['1', 2]` | | options `1` and `2` | What the user picks is sent as a string, or an array of strings for a multiple select. Cast it in the component if you need integers. ### Tags With `data-tags`, users can type new values. Values in the property that have no `</option><option>`, such as tags saved earlier, get one when they are shown, so they appear on the first render. ```blade <div wire:ignore><select multiple data-pharaonic="select2" wire:model="labels" data-tags><option value="urgent">urgent</option></select></div> ``` ### Reacting to Changes `wire:change` on the select runs after the new value is written, so the action sees it: ```blade <div wire:ignore><select data-pharaonic="select2" wire:model="country" wire:change="countryChanged">...</select></div> ``` Select2 itself never fires the native `change` event; the package fires one for selects that have `wire:change`. Change handlers you attach with jQuery receive that event too, so on these selects they run twice. An `updated` hook in the component needs no event at all: ```php title="app/Http/Livewire/Order.php" public function updatedCountry($value) { $this-&gt;city = null; } ``` ## Options There are three ways to configure Select2, from the simplest: 1. the package's shorthand attributes, for the most common options; 2. Select2's own `data-*` attributes; 3. `data-options`, a JSON object, for everything else. ### Shorthand Attributes ```blade <select data-pharaonic="select2" wire:model="country" data-placeholder="Choose a country" data-clear data-search-off>``` | Attribute | Select2 option | | --- | --- | | `data-tags` | `tags: true`: users can type new values | | `data-clear` | `allowClear: true`: shows a clear button | | `data-search-off` | `minimumResultsForSearch: -1`: hides the search field | | `data-parent="#selector"` | `dropdownParent`: opens the dropdown inside that element | | `data-parent` (no value) | `dropdownParent`: the closest modal or dialog | | `data-template="name"` | `templateResult` and `templateSelection`: a function defined with `define()` (see [Templates and Callbacks](#templates)) | A shorthand is on when the attribute is present, with or without a value. `data-clear="false"` turns it off, which helps when Blade decides: `data-clear="{{ $nullable ? 'true' : 'false' }}"`. Select2 shows the clear button only when there is a placeholder. When you turn `data-clear` on without a placeholder, the package sets an empty one, so the button appears without adding text. Use `data-parent` for selects inside modals, so the dropdown opens inside the modal and its search field can take focus. Without a value, it picks the closest `.modal` (Bootstrap), `<dialog>`, or `[role="dialog"]`: ```blade <div class="modal" id="edit-modal"><div wire:ignore><select data-pharaonic="select2" wire:model="type" data-parent>...</select></div></div> ``` With a CSS selector, it uses that element instead: `data-parent="#edit-modal"`. When nothing matches, the dropdown opens in `body` as usual. ### Select2's Own data-* Attributes Select2 reads any option from a `data-*` attribute, with the option name in kebab case. These need no help from the package: | Attribute | Select2 option | | --- | --- | | `data-placeholder="Choose"` | `placeholder` | | `data-width="100%"` | `width` | | `data-language="ar"` | `language` | | `data-dir="rtl"` | `dir` | | `data-theme="bootstrap-5"` | `theme` (load the theme's stylesheet yourself) | | `data-minimum-input-length="2"` | `minimumInputLength` | | `data-maximum-selection-length="3"` | `maximumSelectionLength` | | `data-ajax--url="/api/countries"` | `ajax.url` | :::warning Booleans in Select2's attributes Select2 reads its `data-*` attributes as plain strings, so any non-empty value counts as true: `data-close-on-select="false"` keeps closing the dropdown. Set booleans that have no shorthand in `data-options`. ::: ### data-options Anything else goes in `data-options` as a JSON object: ```blade <select data-pharaonic="select2" wire:model="labels" multiple data-options='{"closeOnSelect": false, "tokenSeparators": [","]}'>``` Use single quotes around the attribute so the JSON can use double quotes. In Blade you can build it from PHP: ```blade <select data-pharaonic="select2" wire:model="country" data-options='@json(["placeholder" =&gt; __("Choose a country"), "allowClear" =&gt; true])'>``` `data-options` can also hold `dropdownParent` as a selector. Invalid JSON, or JSON that is not an object, is reported as `invalid-options` and the select is not mounted. ### Which Wins `data-options` overrides the shorthand attributes. Select2's own `data-*` attributes override both, because Select2 applies them last. Set each option in one place. ### Functions in Options Some Select2 options are JavaScript functions, which attributes cannot hold. Define the function once in JavaScript and use its name in `data-options`. See [Templates and Callbacks](#templates). ### Changing Options Inside `wire:ignore`, Livewire never changes the select, so new attributes from the server are not applied. To change options or the list of `<option>` elements, let Livewire replace the block with a new `wire:key`. See [Dynamic Selects](#dynamic-selects). ## Templates and Callbacks ### Images Without JavaScript Add `data-image` to an `</option><option>` to show an image before its text, in the dropdown and in the selection: ```blade <div wire:ignore><select data-pharaonic="select2" wire:model="country">@foreach ($countries as $country) <option value="{{ $country-&gt;id }}" data-image="{{ asset('flags/'.$country-&gt;code.'.svg') }}">{{ $country-&gt;name }}</option> @endforeach</select></div> ``` The image is 1.25em high, aligned with the text, and has the `pharaonic-select2-image` class for your own styling. Options without `data-image` show their text as usual. A select with its own `templateResult` or `templateSelection` uses those instead. ### Your Own Templates Select2 options such as `templateResult` take functions. Define a function with a name, then use the name in `data-template` or `data-options`. ### define(name, callback) ```js title="resources/js/app.js" Pharaonic.select2.define('flag', (state) =&gt; { if (!state.element) { return state.text } const span = document.createElement('span') span.textContent = `${state.element.dataset.flag} ${state.text}` return span }) ``` ```blade title="resources/views/livewire/profile.blade.php" <div wire:ignore><select data-pharaonic="select2" wire:model="country" data-template="flag"><option value="eg" data-flag="&#127466;&#127468;">Egypt</option><option value="jo" data-flag="&#127471;&#127476;">Jordan</option></select></div> ``` `data-template` sets both `templateResult` and `templateSelection`. To use different functions, name them in `data-options`, which overrides `data-template`: ```blade <select data-pharaonic="select2" wire:model="country" data-template="flag" data-options='{"templateSelection": "flagOnly"}'>``` - A name starts with a letter or digit and continues with letters, digits, `.`, `:`, `_` or `-`. Anything else, or a callback that is not a function, throws an error with the code `invalid-function`. - Defining the same function under the same name again does nothing. A different function under a taken name throws `function-conflict`. - With a bundler, import `define` from the ES module instead of using `window.Pharaonic.select2`. ### Options That Accept a Name | Option | Option | | --- | --- | | `templateResult` | `createTag` | | `templateSelection` | `insertTag` | | `matcher` | `tokenizer` | | `sorter` | `ajax.data` | | `escapeMarkup` | `ajax.processResults` | | | `ajax.transport` | Any other option keeps its JSON value. `ajax.url` stays a string. ### Load Order Call `define` after `@livewireSelect2Scripts` has loaded, for example in a deferred or module script, or import it from the ES module. A select that uses a name that is not defined yet waits: a console warning names the function once, and the select mounts as soon as `define` is called. ### Remote Data ```js title="resources/js/app.js" Pharaonic.select2.define('countries', (data) =&gt; ({ results: data.map((country) =&gt; ({ id: country.id, text: country.name })), })) ``` ```blade <select data-pharaonic="select2" wire:model="country_id" data-options='{"ajax": {"url": "/api/countries", "dataType": "json", "processResults": "countries"}}'> @if ($country) <option value="{{ $country-&gt;id }}" selected>{{ $country-&gt;name }}</option> @endif</select> ``` With remote data, Select2 can only show a value that has an `<option>`. Render the selected one in Blade, as above. :::warning Build markup safely Select2 escapes strings returned by templates. To render markup, return DOM nodes or a jQuery object built with `textContent` or `text()`, as in the examples. Never build HTML strings from option text or user data. ::: ## Dynamic Selects Livewire adds, removes, and re-renders elements. The package follows it. ### Selects Livewire Adds or Removes Selects that appear after a Livewire update, such as a new row from `wire:click="addRow"`, mount and bind after that update. Selects that disappear are cleaned up: their handlers are removed and Select2 is destroyed. ```blade title="resources/views/livewire/invoice.blade.php" @foreach ($rows as $index =&gt; $row) <div wire:key="row-{{ $row['id'] }}"><div wire:ignore><select data-pharaonic="select2" wire:model="rows.{{ $index }}.product">...</select></div></div> @endforeach <button wire:click="addRow">Add row</button> ``` :::tip Key rows by something stable Give each row a `wire:key` that stays with the row, such as an id, not its position. When a row in the middle is removed, position keys shift, and Livewire keeps the wrong widgets. ::: ### Dependent Selects When one select decides the options of another, the second select needs its new `</option><option>` list from the server. There are two ways. **A new wire:key per parent value.** Livewire replaces the ignored block when its key changes. The old widget is cleaned up and the new select mounts with the new options. ```blade <div wire:ignore><select data-pharaonic="select2" wire:model="level">...</select></div><div wire:ignore wire:key="group-{{ $level }}"><select data-pharaonic="select2" wire:model="group"><option value="">Choose a group</option> @foreach ($groups as $id =&gt; $name) <option value="{{ $id }}">{{ $name }}</option> @endforeach</select></div> ``` **No wire:ignore.** Livewire updates the select, and the package rebuilds the widget after each update. ```blade <div><select data-pharaonic="select2" wire:model="group">...</select></div> ``` The first way keeps the widget untouched by unrelated requests. The second is simpler, but every request that re-renders the component rebuilds the widget and closes an open dropdown. Reset the child property when the parent changes: ```php title="app/Http/Livewire/Enrollment.php" public function updatedLevel() { $this-&gt;group = ''; } ``` :::warning Key ignored blocks that come and go Livewire 1 compares siblings by position. When ignored blocks can appear or disappear next to each other, give each a unique `wire:key`. ::: ### Nested Components and Many Selects Each select binds to the closest Livewire component around it. A select in a nested component writes to that component, never to the parent. Any number of selects can share a page. `data-component-id` binds a select to a specific component wherever it is. In a Livewire 1 view the id is `$this-&gt;id`. An empty value means the closest component. ### Selects You Add Yourself Selects you add with JavaScript, outside a Livewire update, need one call: ```js Pharaonic.assistant.scan(container) // mounts the selects in container Pharaonic.assistant.destroy(container) // cleans them up ``` ### Turbolinks Widgets are cleaned up before Turbolinks caches a page and mounted again when it comes back. ## API Reference ### Markup | Attribute | Value | | --- | --- | | `data-pharaonic` | `select2` | | `wire:model` | Property name or dot path; modifiers accepted | | `data-property` | Property name or dot path; wins over `wire:model` | | `data-tags` | `tags: true`; `"false"` turns it off | | `data-clear` | `allowClear: true`, with an empty placeholder when none is set; `"false"` turns it off | | `data-search-off` | `minimumResultsForSearch: -1`; `"false"` turns it off | | `data-parent` | `dropdownParent` from a CSS selector; without a value, the closest `.modal`, `<dialog>`, or `[role="dialog"]` | | `data-template` | Named function for `templateResult` and `templateSelection` | | `wire:change` | Runs after the new value is written | | `data-options` | JSON object passed to Select2; overrides the shorthands | | `data-component-id` | Component id; empty or absent means the closest component | On `<option>`: | Attribute | Value | | --- | --- | | `data-image` | Image URL shown before the option text | ### Browser API Available as `window.Pharaonic.select2` and as named exports of `dist/livewire-select2.esm.js`. | Method | Description | Returns | | --- | --- | --- | | `define(name, callback)` | Names a function for function options in `data-options` | `undefined` | Deprecated aliases, on `window.Pharaonic.Select2`: | Method | Description | | --- | --- | | `init()` | Calls `Pharaonic.assistant.scan(document)` | | `load(element)` | Calls `Pharaonic.assistant.scan(element)`; accepts an element or a jQuery object | ### Events | Event | Direction | Purpose | | --- | --- | --- | | `pharaonic:assistant:error` | dispatched on `window` | Failures while mounting, updating, or cleaning up (see the Livewire Assistant diagnostics) | | `pharaonic.select2.init` | listened on `window` | Deprecated: scans the document | | `pharaonic.select2.load` | listened on `window` | Deprecated: scans `event.detail.target` | ### Error Codes | Code | Raised when | Channel | | --- | --- | --- | | `invalid-function` | `define()` got an invalid name or a callback that is not a function | thrown | | `function-conflict` | `define()` got a different function for a taken name | thrown | | `select2-missing` | jQuery or Select2 is not on `window.jQuery` once the page has loaded | cause of `mount-failed` | ### Laravel | Name | Purpose | | --- | --- | | `@livewireSelect2Scripts` / `@livewireSelect2Scripts(['nonce' =&gt; $nonce])` | Renders the Assistant runtime and the integration once per page | | `pharaonic.livewire-select2.script` | Route name of `GET /pharaonic/livewire-select2/select2.js` | | `Pharaonic\Livewire\Select2\Select2ServiceProvider` | Auto-discovered service provider | | `<:scripts></:scripts>` | Deprecated: renders `@livewireSelect2Scripts` | | `livewire-select2` publish tag | Deprecated: copies the script to `public/vendor/pharaonic/pharaonic.select2.min.js` | | `select2::messages.*` | Error messages of the directive, in English and Arabic | | `pharaonic`, `pharaonic-translations`, `select2-translations` publish tags | Copy the translations to `resources/lang/vendor/select2` | ### Script Endpoint The directive points at this route; you never call it yourself, but proxies and CSP rules see it. ```http no-copy GET /pharaonic/livewire-select2/select2.js?id=0d8eee40cb71f6d7 HTTP/1.1 ``` ```http no-copy HTTP/1.1 200 OK Content-Type: application/javascript; charset=utf-8 Cache-Control: immutable, max-age=31536000, public X-Content-Type-Options: nosniff ``` | Request | Response | | --- | --- | | `id` matches the hash of the installed script | `200`, cached for a year (`immutable`) | | `id` is missing or outdated | `200`, same script, `Cache-Control: no-cache` | The route has no middleware group, so it starts no session and sets no cookies. It takes no other parameters and returns no error responses of its own. ## Compatibility Every combination below installs with Composer and passes the PHP suite and the real-browser suite (real Livewire 1 components, the real Livewire Assistant runtime, jQuery, and Select2, driven in real browsers) with lowest and highest dependencies. | Line | Livewire | Laravel | PHP | Browsers | | --- | --- | --- | --- | --- | | 1.x | 1.3.0 to 1.3.9, except 1.3.7 | 7.30+ | 7.4 | Chromium, Firefox, WebKit | | 1.x | 1.3.0 to 1.3.9, except 1.3.7 | 8.75+ | 7.4 | Chromium, Firefox, WebKit | The browser suite uses jQuery 4 and Select2 4.1. ### Why PHP 7.4 Every Livewire 1 release requires PHP 7. PHP 7.4 is the oldest PHP the package's test and analysis tools run on. ### What Livewire 1 Cannot Do Livewire 1 has no deferred updates, so every write is live, whatever the `wire:model` modifiers. :::warning Livewire 1 security Livewire 1 no longer receives fixes. CVE-2024-47823 (remote code execution through file uploads) affects every Livewire release before 2.12.7, including all of Livewire 1. This package does not use file uploads, but your application does if it uses Livewire's `WithFileUploads`. Plan your upgrade. ::: ## Examples ### 1. Edit Form in a Modal The server fills the form when the modal opens; the select shows the saved value and opens its dropdown inside the modal. - ===Component ```php title="app/Http/Livewire/Items.php" <?php namespace App\Http\Livewire; use App\Models\Category; use App\Models\Item; use Livewire\Component; class Items extends Component { public $editing = false; public $itemId; public $category_id; public function edit($id) { $item = Item::findOrFail($id); $this->itemId = $item-&gt;id; $this-&gt;category_id = $item-&gt;category_id; $this-&gt;editing = true; } public function render() { return view('livewire.items', ['categories' =&gt; Category::pluck('name', 'id')]); } } ``` - ===View ```blade title="resources/views/livewire/items.blade.php" <div><div class="modal" style="display: {{ $editing ? 'block' : 'none' }}"><div wire:ignore><select data-pharaonic="select2" wire:model="category_id" data-placeholder="Category" data-clear data-parent><option value=""></option> @foreach ($categories as $id =&gt; $name) <option value="{{ $id }}">{{ $name }}</option> @endforeach</select></div></div></div> ``` ### 2. Country and City The city list depends on the country. A new `wire:key` replaces the city select whenever the country changes. - ===Component ```php title="app/Http/Livewire/Address.php" public $country_id = ''; public $city_id = ''; public function updatedCountryId() { $this-&gt;city_id = ''; } public function render() { return view('livewire.address', [ 'countries' =&gt; Country::pluck('name', 'id'), 'cities' =&gt; City::where('country_id', $this-&gt;country_id)-&gt;pluck('name', 'id'), ]); } ``` - ===View ```blade title="resources/views/livewire/address.blade.php" <div><div wire:ignore><select data-pharaonic="select2" wire:model="country_id"><option value="">Country</option> @foreach ($countries as $id =&gt; $name) <option value="{{ $id }}">{{ $name }}</option> @endforeach</select></div><div wire:ignore wire:key="cities-{{ $country_id }}"><select data-pharaonic="select2" wire:model="city_id"><option value="">City</option> @foreach ($cities as $id =&gt; $name) <option value="{{ $id }}">{{ $name }}</option> @endforeach</select></div></div> ``` ### 3. Invoice Rows Each row has its own select bound to its own array item. ```blade title="resources/views/livewire/invoice.blade.php" <div>@foreach ($rows as $index =&gt; $row) <div wire:key="row-{{ $row['id'] }}"><div wire:ignore><select data-pharaonic="select2" wire:model="rows.{{ $index }}.product_id"><option value="">Product</option> @foreach ($products as $id =&gt; $name) <option value="{{ $id }}">{{ $name }}</option> @endforeach</select></div><button wire:click="removeRow({{ $index }})">Remove</button></div> @endforeach <button wire:click="addRow">Add row</button></div> ``` ### 4. Tags Users pick existing tags or type new ones; saved tags show on load even without an option. ```blade title="resources/views/livewire/post-form.blade.php" <div wire:ignore><select multiple data-pharaonic="select2" wire:model="tags" data-tags data-options='{"tokenSeparators": [","]}'>@foreach ($suggestions as $tag) <option value="{{ $tag }}">{{ $tag }}</option> @endforeach</select></div> ``` ## Troubleshooting ### A validation message does not show The `@error` is inside the `wire:ignore` block, which Livewire never updates. Move it outside, next to the block. See [Basic Usage](#basic-usage). ### Nothing happens and there is no widget Check the console. `select2-missing` means jQuery or Select2 is not on `window.jQuery`: load them, or with a bundler set `window.jQuery` and call `select2()` (see [Installation](#installation)). Make sure `@livewireSelect2Scripts` is on the page. ### "$ is not a function" The package never uses `$`; it reads `window.jQuery` when a select mounts. The error comes from code that expects a global `$`. With a bundler, set `window.jQuery` as shown in [Installation](#installation). ### The widget disappears or resets after a request The select is outside `wire:ignore` and the package rebuilds it after each update, or Livewire replaced the block. Wrap the select in `wire:ignore` unless you want the server to change its options. ### New options from the server do not appear Inside `wire:ignore`, Livewire never changes the select. Give the ignored block a `wire:key` that changes with the data, or remove `wire:ignore`. See [Dependent Selects](#dynamic-selects). ### My jQuery change handler runs twice The select has `wire:change`. Select2 fires its own jQuery change event, and the package fires a native one so `wire:change` runs. Use `wire:change` or the `updated` hook instead of the jQuery handler, or remove `wire:change`. ### The value is a string, but my property is an integer Select2 works with strings. Cast in the component, for example in an `updated` hook. ### The dropdown opens behind a modal, or its search field cannot take focus Add `data-parent` to the select. It opens the dropdown in the closest `.modal`, `<dialog>`, or `[role="dialog"]`; give it a selector when the modal is something else. ### A select in a nested component updates the parent Remove a `data-component-id` that names the parent, or leave the attribute out: the closest component is used. ### Composer refuses to install Livewire 1 or Laravel 7 or 8 Those releases have unfixed security advisories. See the warning in [Installation](#installation). ## Upgrade Guide ### Within 1.x Every 1.x release is compatible with the one before it, so `composer update` is enough. No markup, directive, or JavaScript change is needed. Deprecated aliases keep working on every 1.x release. Move new code to their replacements whenever you like: | Deprecated | Use instead | | --- | --- | | `<:scripts></:scripts>` | `@livewireSelect2Scripts` | | `php artisan vendor:publish --tag=livewire-select2` and your own `<script>` tag|`@livewireSelect2Scripts`,which serves the script from the package route||`Pharaonic.Select2.init()`,`Pharaonic.Select2.load()`|`Pharaonic.assistant.scan(element)`||The `pharaonic.select2.init` and `pharaonic.select2.load` events|`Pharaonic.assistant.scan(element)`|If you published `vendor/pharaonic/pharaonic.select2.min.js`,switch to the directive and delete the published file:the file needs the Livewire Assistant runtime,which only the directive loads.### From 1.0 to 1.2 Releases 1.0 to 1.2 were built for Livewire 2,not Livewire 1,and Composer never moves them to 1.3 or later.Their successor is the 2.x line;follow the upgrade guide in the 2.x documentation.### To Livewire 2 Each Livewire major has its own line.When your application moves to Livewire 2,require the 2.x line:```bash title="Terminal"no-line-numbers composer require pharaonic/livewire-select2:^2.0 ```||1.x|2.x||---|---|---||PHP|7.4|8.0 to 8.3||Livewire|1.3.0 to 1.3.9,except 1.3.7|2.12.7+||Laravel|7.30+,8.75+|7.30+,8.75+,9,10|Your markup,attributes,and the directive stay the same.One difference:on Livewire 1 every write is live,whatever the `wire:model` modifiers;on Livewire 2,`wire:model.defer` sends the value with the component's next request.</script></dialog></option></dialog></option></select></option></select></select></dialog></select></option></select></select></select></p></body></html>