Skip to content

Instantly share code, notes, and snippets.

@MACscr
Forked from localdisk/Tagify.php
Created May 24, 2021 22:03
Show Gist options
  • Save MACscr/2aa36ef77a4b6252cdc46102ed32bbcd to your computer and use it in GitHub Desktop.
Save MACscr/2aa36ef77a4b6252cdc46102ed32bbcd 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/tagify@3.11.1/dist/tagify.min.css">
@endpush
@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/@yaireo/tagify@3.11.1/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,
]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment