Implementing Full Text Search in Laravel Scout

Implementing a robust search functionality is crucial for many web applications. Laravel Scout, a powerful search package, simplifies the process of integrating full-text search capabilities into Laravel projects.

In this tutorial, we will explore the steps involved in implementing full-text search using Laravel Scout. By the end, you’ll have a clear understanding of how to harness the power of Scout to enhance your Laravel applications’ search capabilities.

What is Full-Text Search?

Full-text search is a search technique that allows you to search for keywords or terms within the entire content of a document. Unlike traditional searches that focus on specific fields or metadata, full-text search considers the context and relevance of words within the document’s body, titles, subtitles, and other textual content.

It helps users find relevant information by matching their search queries with the actual content of documents, rather than relying solely on predefined fields or tags.

What is Laravel Scout?

Laravel Scout is an official Laravel package that provides a simple and elegant way to add full-text search to your Laravel applications. It seamlessly integrates with popular search engines like Algolia, Elasticsearch, and more.

Scout allows you to perform advanced search queries on your models and retrieve relevant results efficiently.

Set up Laravel Scout and the Search Engine

Before starting, let’s assume your Laravel application is up and running. Then, install the Scout package by running the following command in your terminal:

composer require laravel/scout

Next, install the driver for your chosen search engine. For example, if you want to use Algolia, run:

composer require algolia/algoliasearch-client-php

After installing the driver, let’s configure the .env file with the necessary credentials for your search engine. Refer to the documentation (https://laravel.com/docs/10.x/scout) of your chosen search engine for the specific configuration details.

Here, we are using algoliasearch. Open the .env file and add the below code in it.

ALGOLIA_APP_ID=XXXXXX
ALGOLIA_SECRET=XXXXXXXXXXXXXXXXXXXXXXXXXXXX

In your Laravel application, open the config/scout.php file. Here, you can specify the driver you want to use for Scout. For example, to use Algolia, set the driver option to algolia.

Prepare your Models for Search

To enable full-text search on a specific model, we have to make sure it uses the Laravel\Scout\Searchable trait. This trait adds the necessary methods and event listeners to allow your models to be searchable with full-text search functionality.

<?php 
namespace App\Models;

use Laravel\Scout\Searchable;

class Post extends Model
{
    use Searchable;

    // Model code...
}

Indexing and Searching

Once your model is ready, you can start indexing and searching. Indexing refers to the process of populating your search engine’s index with your model’s data. To perform indexing, use the searchable() method provided by the Searchable trait.

Next, we would like to configure the fields that should get indexed in the first place. Of course, you don’t want to index all the fields of your model in Algolia to keep it effective and lightweight. More often than not, you won’t need it.

public function toSearchableArray()
{
    $array = $this->toArray();
     
    return [
        'id' => $array['id'],
        'title' => $array['title'],
        'slug => $array['slug],
    ];
}

Here, we have specified which columns will be searched. So, whenever we call the search() method it will search within only those fields and improve response time.

Creating a Search Route and Controller

For this example, we will just perform a search based on the URL query parameter. Let’s create a search route and controller to handle search requests and display the search results.

First, define a route in your routes/web.php file:

use App\Http\Controllers\SearchController;

Route::get('/search', 'SearchController@index')->name('search.index');

Now let’s create a controller for handling search functionality. Open your terminal and enter the below command to create a controller:

php artisan make:controller SearchController

Open the app/Http/Controllers/SearchController.php file and add the following code:

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;

class SearchController extends Controller
{
    public function index(Request $request)
    {
        $query = $request->input('query');
        $posts = Post::search($query)->get();

        return view('search.index', compact('posts'));
    }
}

In the above controller, we have created an index method that is called whenever the user search for something. In the index method, first of all, it will get a query parameter from the URL and perform a full-text search using Laravel Scout.

The search() method will handle full-text search functionality and perform a search on our specific columns of model configurations. At last, it will return data to view where the user can see search results.

However, you can perform other Eloquent methods like where GroupBy or paginate as normal.

Create a Search Results View

Create a new blade view file called index.blade.php in the resources/views/search directory. In this view, you can display the search results as desired.

For example, you can iterate over the $posts variable to display the title and content of each search result:

<!DOCTYPE html>
<html>
<head>
    <title>Search Results</title>
</head>
<body>
    <h1>Search Results</h1>

    @foreach($posts as $post)
        <h2>{{ $post->title }}</h2>
        <p>{{ $post->content }}</p>
    @endforeach
</body>
</html>

Conclusion

Implementing full-text search using Laravel Scout enhances the search capabilities of your Laravel applications. With the seamless integration of popular search engines and the flexibility of advanced search queries, you can deliver more accurate and efficient search results to your users.

There are more in-depth settings available with Laravel Scout you can use it as per your requirement like customizing search engines or using cache services.