Search with autocomplete

Is there a package already? Something like typehead would be great

1 Like

Hey, @Alexandru

You can use livewire with AlpineJs to make autocomplete happened.

In your blade:

<div x-data="{isTyped: false}">
    <div>
        <div class="relative">
            <input type="text"
                placeholder="{{__('Search ...')}}"
                x-on:input.debounce.400ms="isTyped = ($event.target.value != '')"
                autocomplete="off"
                wire:model.debounce.500ms="search"
                aria-label="Search input" />
        </div>
        {{-- search box --}}
            <div x-show="isTyped" x-cloak>
                <div>
                    <div>
                            @forelse($articles as $article)
                                <div>
                                    <ul>
                                        <li>
                                            <a href="{{route('blog.show', $article->slug)}}">
                                                {{Str::limit($article->title, 40)}}
                                            </a>
                                            <a href="{{route('category.show', $article->category->slug ?? 'uncategorized')}}">
                                                {{$article->category->name}}
                                            </a>
                                        </li>
                                    </ul>
                                </div>
                            @empty
                                <div x-cloak>
                                    {{$isEmpty}}
                                </div>
                            @endforelse
                    </div>
                </div>
            </div>
    </div>

</div>

In your search component

    public $search, $isEmpty = '';
    public function render()
    {
        if (!is_null($this->search)) {
            $articles = Post::search($this->search)
                ->take(5)
                ->get();
            $this->isEmpty = '';
        } else {
            $articles = [];
            $this->isEmpty = __('Nothings Found.');
        }

        return view('search', [
            'articles' => $articles,
        ]);
    }

And you can add this method in your model or use Laravel Scout Package.

    public static  function search($searchKey)
    {
        return self::where('title', 'LIKE', '%' . $searchKey . '%')
            ->orWhere('body', 'LIKE', '%' . $searchKey . '%')->with('category');
    }

PS: because I don’t know what framework do you use to style your pages, I attended to paste vanilla HTML and, in this case you can use your own style/classes.

3 Likes