Tags

Using the Tags field with Spatie Laravel tags

protected function fields()
{
    return [
        Tags::make('Tags')//The field expects a comma separated array.
            ->default($this->model->exists ? $this->model->tags()->pluck('name') : [])
            ->relation() //save the items with saveFoo() hook, se below
            ->deferEntangle(false);
            //->errorMsg(...)->help(...)->placeholder(...) //default in translation files
            //->rules(...); //applied to each tag, default = 'string|alpha_num|between:3,25'
    ];
}

Save the tags

If your tags are a relationship, you probably want to save the data manually.

protected function saveTags($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);
}

Translation files

The default values for some slots are in the translation files

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

Headless

Component

public array $tagsDefault = [];
public array $tags = [];

//protected $rules = [ ... ];

public function mount(?User $user)
{
    $this->mount_form($user);
    $this->tagsDefault = $this->model->exists ? $this->model->tags()->pluck('name') : []
}

protected function submit() { ... validate, sync model tags }

public function render() { ... render the view }

blade view

<form wire:submit.prevent="submit">

    <x-tall-tags :field="Tags::blade('Tags')->default($tagsDefault)" />
    
    <button type="submit">Submit</button>
    
</form>

Last updated