Livewire combobox package

https://github.com/sertxudeveloper/livewire-combobox

Codecov Test coverage

Add combobox to your Livewire forms

Do you have a large dataset, and you need to be able to display it in a dropdown?

When a basic select input is not enough, you can use a combobox!

A combobox works like a select input, but instead of a dropdown, it displays a list of options that can be filtered by typing.

You will no longer need to download all the data at the startup, just get the data you're looking for.

Installation

You can install the package via composer:

composer require sertxudeveloper/livewire-combobox

Usage

Once you have installed the package, you can use it in your Livewire forms.

First, you need to execute the following command in your terminal:

php artisan combobox:make UsersCombobox -m User

This will create a new component in the app/Livewire directory.

The new UsersCombobox component will look like this:

<?php

namespace App\Livewire;

use App\Models\User;
use SertxuDeveloper\LivewireCombobox\Components\Combobox;

class UsersCombobox extends Combobox
{

    /** @var class-string<Model> $model */
    public string $model = User::class;

}

As you can see, the $model property is set to the User model. This means that the component will be able to query the database using this model.

By default, the component will display the name column of the model. You can change this by setting the labelColumn property:

/**
 * The column to be shown as the label.
 *
 * @var string
 */
public string $labelColumn = 'title'; // Default: 'name'

To start using the component, you need to add it to your Livewire form.

<livewire:users-combobox>
@livewire('users-combobox')

You can also pass some parameters to the component:

<livewire:users-combobox name="author" label="Author" placeholder="Select a user">

Warning
If you don't pass any parameters, the component will use the default values.
It's recommended to pass the parameters to the component.
You can also add the values overriding the default values in the class.

Events

While interacting with the component, some events might be fired.

The name of the events depends on the component name, this allows you to have more than one combobox in your form.

These events will be fired up, so the parent component can react to the user interaction.

Note
The selected event contains the selected model as a parameter.

Adding filters

You can filter the results by adding filters to the component.

/**
 * Apply filters to the query.
 *
 * @param Builder $query
 * @return void
 */
protected function filter(Builder $query): void {
    $query->where('email', 'like', "%@example.com");
}

The filter method receives the query builder as a parameter, so you can add as many filters as you want.

The filters will be applied to the query before fetching the results, so you can use them to limit the options given to the user.