Member-only story

Site wide Search in Laravel with Scout

Sam Ngu
7 min readOct 28, 2020

--

Watch this tutorial on Youtube:

The “Search everything” box in the navigation bar is a very common feature in modern web app. I like it a lot, but implementing it in our own web app could be challenge. Here’s my solution to tackle this problem.

Implementing site wide full text search is not as straight forward as you may think. Photo by Markus Winkler on Unsplash

Prerequisite

  1. Laravel Scout (I’m using TNTSearch driver here)
  2. Intermediate knowledge of Laravel

Note: I’m using Laravel 8 at the time of writing this article.

Full source code for this tutorial is available here. I will only cover the core implementation in this article. The source code is commented, please check it out if you need more details.

TLDR; If you don’t feel like reading / implementing your own, I’ve created a package for this.

The plan

Here’s a high-level overview on how are we going to achieve this.

  1. Create a global site search endpoint.
  2. Load all available models in the model folder.
  3. Loop through the models, and call the Laravel Scout’s ::search() function on each model.
  4. Each record found should include:
    a. match — the match found in our model records
    b. model — the related model name, eg Post , User
    c. view_link — the URL to navigate to the target resource page.
  5. Combine all results together and load them in an API Resource Collection and return to the front-end.

Show me the Code

Okay…okay, here we go. I assumed you have already installed Laravel Scout and TNTSearch at this point.

Set up an API routes to perform the full site search

// /routes/api.php
Route::get('/site-search'…

--

--

Responses (1)

Write a response