TagsSearch

Example using TagsSearch with Spatie Tags

1. Setup the component

//search RESULT
protected array $tagsSearchResult = [];

//search INPUT
public string $tagsSearchInput = "";

//Set the search input rules, 
//to validate the incoming $value before searching the Database.
protected $rules = [ 'tagsSearchInput' => ... ]; 

2. Update the search result

// update search RESULT when search INPUT is changed
public function updatedTagsSearchInput($value) //function name = CamelCased search input property name
{
    //validation rules for $value are set in the $rules property
    //dynamically update the search result, consider ->take(...) in an eloquent query
    if (filled($value)) {
        $this->tagsSearchResult = ['Tag1', 'Tag2', 'Tag3', 'Tag4', 'Tag5', 'Tag6', 'Tag8', 'Tag9', 'Tag10'];
    } else {
        $this->tagsSearchResult = []; //if you want to clear the search options if the user clears the search input
    }
}

3. Define the field

protected function fields()
{
    return [
        TagsSearch::make('TagsSearch', 'temporary_tags')
            ->searchKey('tagsSearchInput')//search INPUT property name
            ->fieldWidth('w-full sm:max-w-sm')
            ->listWidth('w-full max-w-xs')
            ->options($this->tagsSearchResult) //search RESULT property
            ->default(optional($this->model)->exists ? $this->model->tags()->pluck('name') : []) //model VALUE, or empty array
            ->debounce(500)
            ->allowNew() //or disableNew(), true by default
            ->custom() //saveFoo()
            // ->errorMsg(...)->help(...)->placeholder(...) //default in translation files
            // ->rules(...) //optionally see below
    ];
}

4. Save the tags

protected function saveTemporaryTags($validated_array)
{
    //example; remove duplicates, ucfirst on each array item
    $cleaned = array_map('ucfirst', array_unique($validated_array));
    
    //Spatie sync tags
    $this->model->syncTags($cleaned);
}

Methods

->help()->errorMsg()->placeholder()

Translation files contains defaults

->rules() (optional)

Rules apply to each tag. A default rule already exists in the Tags class; 'string|alpha_dash|between:3,25'

Headless

Follow the instructions above and add this to your blade view

<x-tall-tags-search 
  :field="TagsSearch::blade('TagsSearch', 'temporary_tags')
    ->searchKey('tagsSearchInput')//search INPUT property name
    ->fieldWidth('w-full sm:max-w-sm')
    ->listWidth('w-full max-w-xs')
    ->options($this->tagsSearchResult) //search RESULT property
    ->default(optional($this->model)->exists ? $this->model->tags()->pluck('name') : []) //model VALUE, or empty array
    ->debounce(500)
    ->allowNew() //or disableNew(), true by default
    ->custom()"
/>

Last updated