Skip to content

Instantly share code, notes, and snippets.

@localdisk
Last active October 17, 2022 17:04
Show Gist options
  • Save localdisk/6f62cdff2fd96bf5d4fd8841ac74c732 to your computer and use it in GitHub Desktop.
Save localdisk/6f62cdff2fd96bf5d4fd8841ac74c732 to your computer and use it in GitHub Desktop.
Livewire Tagify Component
<div wire:ignore class="mb-4">
<label class="label" for="tagify">
Tags
</label>
<input
type="text"
id="tagify"
class="shadow-sm appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight"
>
</div>
@push('styles')
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@yaireo/[email protected]/dist/tagify.min.css">
@endpush
@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/@yaireo/[email protected]/dist/tagify.min.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var input = document.getElementById('tagify')
var tagify = new Tagify(input, {
whitelist : [
@foreach($tags as $tag)
'{{ $tag }}'@if(! $loop->last), @endif
@endforeach
]
})
input.addEventListener('change', onChange)
function onChange(e){
@this.call('changeTags', e.target.value)
}
})
</script>
@endpush
<?php
namespace App\Http\Livewire;
use App\Models\Tag;
use Illuminate\View\View;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\Container\BindingResolutionException;
use Livewire\Component;
class Tagify extends Component
{
/** @var array */
public array $tags;
/**
* mount.
*
* @param array $tags
* @return void
*/
public function mount(?array $tags = []): void
{
$this->tags = $tags;
}
/**
* change tags.
*
* @param string $tags
* @return void
*/
public function changeTags(string $tags): void
{
if (empty($tags)) {
return;
}
$changed = collect(json_decode($tags))->pluck('value')->toArray();
$this->emitUp('changeTags', $changed);
}
/**
* render.
*
* @return View|Factory
* @throws BindingResolutionException
*/
public function render()
{
$this->tags = $this->tags ?: Tag::all()->pluck('name')->toArray();
return view('livewire.tagify', [
'tags' => $this->tags,
]);
}
}
@MACscr
Copy link

MACscr commented May 24, 2021

oh man, just randomly found this and could really save me some time. This working well for you?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment