Step-By-Step Guide To Setting Up A Full-Text Search In Laravel Using Scout

Step-By-Step Guide To Setup A Full-Text Search In Laravel Using Scout
 

What Do You Mean By Full-Text Search?

According to Wikipedia, Full-Text Search is a technique of searching a single computer-stored document or a collection in the full-text database. Here, the search engine inspects all the words stored in a particular document.

According to Techopedia, Full-Text Search is a comprehensive method that compares every word of the search request against every word written in report or database.

The Full-Text Search allows users to navigate content-rich websites with ease.

When To Use Full-Text Search?
  • Search on multiple columns at one go.
  • Sort the results.
  • Optimize the query performance.
  • Utilize the advanced search pattern.
  • Use your MySQL server.

So far, we have analyzed the basics of Full-Text Search. Now, we’re going to provide you with a step-by-step guide on setting up a Full-Text Search in Laravel web app.

So, let’s get this started right now.!

  1. <iframe src="https://giphy.com/embed/26h0poAzDM5h8gHWE" width="480" height="263" frameBorder="0" class="giphy-embed" allowFullScreen>  
  2. </iframe>  
  3. <p><a href="https://giphy.com/gifs/bbmas-bbmas-2016-26h0poAzDM5h8gHWE">via GIPHY</a></p> 

Step-By-Step Guide To Set Up A Full-Text Search In Laravel

  • Step 1: Understanding Scout Library
  • Step 2: Installing Scout & Algolia
  • Step 3: Making Models Indexable & Searchable
  • Step 4: Implementing Full-Text Search

Step 1 - Understanding Scout Library

For setting up a Full-Text Search in Laravel, we’re going to use Scout. It’s a library which makes the implementation process very easy. So, let’s understand about that in detail.

What Is Laravel Scout?

As per the official documentation, Laravel Scout is a driver-based & straightforward solution. It adds Full-Text Search to Eloquent Models. The library makes use of model observers. The reason for that is to keep search index in sync with Eloquent records.

Laravel Scout's prime job is to look after the index changes. Now, the question is, where will the shift happen in an index? It depends on the type of driver that you will use with Scout.

The Scout library assists Algolia. It’s a cloud-based search engine API used in conjunction with Scout for Full-Text Search implementation.

Step 2 - Installing Scout & Algolia

In this section, we’re going to provide the installation procedure for Scout & Algolia. First of all, you need to manage the server configurations.

For that purpose, installing all the dependencies for the Scout library is essential. The reason behind that is, it will allow Scout library to work with your existing Laravel application.

To install the Scout library using the composer, use the following code:

  1. $composer require laravel/scout 

Once you execute this code, the Scout library will get installed. After completing the installation part, the next step is to inform the Laravel about that.

For that purpose, we’re going to make use of Service Providers. If you’re someone who is working as a Laravel Developer, then you must know about this concept.

Service Providers allow you to configure any new service in the existing application. So, whenever you want to add any new service in Laravel, add an associated service provider entry in config/app.php

Here, you need to add ScoutServiceProvider to the list of service providers in config/app.php as shown in the coding snippet below,

  1. 'providers' => [  
  2.    /* 
  3.    * Application Service Providers... 
  4.    */  
  5.    App\Providers\AppServiceProvider::class,  
  6.    App\Providers\AuthServiceProvider::class,  
  7.    App\Providers\BroadcastServiceProvider::class,  
  8.    App\Providers\EventServiceProvider::class,  
  9.    App\Providers\RouteServiceProvider::class,  
  10.    Laravel\Scout\ScoutServiceProvider::class,  
  11. ], 

After using this code, Laravel will surely become aware of ScoutServiceProvider.

There is a configuration file associated with the Scout library. With the help of that, you can set API credentials. Now, publish the assets that the Scout library provides.

  1. $ php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"  
  2. Copied File [/vendor/laravel/scout/config/scout.php] To [/config/scout.php]  
  3. Publishing complete. 

The next thing you need to do is to create an account with Algolia. It will allow us to get access to the API credentials. For that purpose, move to the official website.

Step-By-Step Guide To Setup A Full-Text Search In Laravel Using Scout
Now, click on the ‘SIGN UP’ button which will open up a whole new window.
 
Step-By-Step Guide To Setup A Full-Text Search In Laravel Using Scout
 
Fill in all the details & create an account after which you’ll get access to API Documentation. Currently, Algolia provides support for 14 different programming languages. You have to choose Laravel out of all the options & then, you will get access to the API.

After getting the details about API, it's time to configure the settings in a config/app.php file.

  1. <?php  
  2. return [  
  3. /* 
  4. |-------------------------------------------------------------------------- 
  5. | Default Search Engine 
  6. |-------------------------------------------------------------------------- 
  7. */  
  8. 'driver' => env('SCOUT_DRIVER''algolia'),  
  9. /* 
  10. |-------------------------------------------------------------------------- 
  11. | Index Prefix 
  12. |-------------------------------------------------------------------------- 
  13. */  
  14. 'prefix' => env('SCOUT_PREFIX'''),  
  15. /* 
  16. |-------------------------------------------------------------------------- 
  17. | Queue Data Syncing 
  18. |-------------------------------------------------------------------------- 
  19. */  
  20. 'queue' => env('SCOUT_QUEUE', false),  
  21. /* 
  22. |-------------------------------------------------------------------------- 
  23. | Chunk Sizes 
  24. |-------------------------------------------------------------------------- 
  25. */  
  26. 'chunk' => [  
  27. 'searchable' => 500,  
  28. 'unsearchable' => 500,  
  29. ],  
  30. /* 
  31. |-------------------------------------------------------------------------- 
  32. | Soft Deletes 
  33. |-------------------------------------------------------------------------- 
  34. */  
  35. 'soft_delete' => false,  
  36. /* 
  37. |-------------------------------------------------------------------------- 
  38. | Algolia Configuration 
  39. |-------------------------------------------------------------------------- 
  40. */  
  41. 'algolia' => [  
  42. 'id' => env('ALGOLIA_APP_ID''STQK4DEGMA'),  
  43. 'secret' => env('ALGOLIA_SECRET''6ef572194f70201ed7ad102cc9f90e05'),  
  44. ],  
  45.   
  46. ]; 

Here, we have the set value of SCOUT_DRIVER to algolia. Therefore, you need to configure the settings for the Algolia driver. You need to set id & secret for Algolia account.

The environment variables can fetch values. So, you need to set them in the .envfile.

Once you’ve correctly set all the variables in the environment file, the next thing is to install Algolia PHP SDK.

To install the SDK, you need to execute the following code:

  1. $composer require algolia/algoliasearch-client-php 

Now, you’re done with managing all the dependencies. It will help you to post as well as index the data.

Step 3 - Making Models Indexable & Searchable

So far, you must have successfully set up the Scout & Algolia libraries. In this section, we’ll analyze the methods to index the existing data & retrieve the search results from Algolia.

Here, we’re assuming that you have a default Post model in your web application. The next thing is to add Laravel\Scout\Searchable in the Post model. The reason for doing this is to make the model searchable.

  1. <?php  
  2. namespace App;  
  3. use Illuminate\Database\Eloquent\Model;  
  4. use Laravel\Scout\Searchable;  
  5. class Post extends Model  
  6. {  
  7.    use Searchable;  
  8.    protected $dates = [  
  9.       'created_at',  
  10.       'updated_at'  
  11.    ];  

Once you execute this code, Laravel will sync the previous records with Algolia index whenever a post is added, updated or deleted. That means the model has now become search-friendly.

The next thing that you should do is to configure the fields that you want to index. For that purpose, add the toSearchableArray in the model class.

  1. public function toSearchableArray()  
  2. {  
  3.    $array = $this->toArray();  
  4.    return array('id' => $array['id'],'name' => $array['name']);  

Once you execute this code, you can import & index the existing records. That’s where the role of Scout library comes into play.

With the help of this library, you need to use the following artisan command for the indexing purpose.

  1. $php artisan scout:import "App\Post" 

Once you execute this command, it will import all the records of the Post model. After that, the records will index easily.

Step 4 - Implementing Full-Text Search

In this section, we’re going to provide you with a live example of how to perform a full-text search & CRUD operations in Laravel with the Algolia index.

For that purpose, create an app/Http/Controllers/SearchController.php file and add the following code:

  1. <?php  
  2. namespace App\Http\Controllers;  
  3. use App\Http\Controllers\Controller;  
  4. use App\Post;  
  5. class SearchController extends Controller  
  6.    {  
  7.    public function query()  
  8.    {  
  9.       $posts = Post::search('title')->get();  
  10.       foreach ($posts as $post) {  
  11.       // ...  
  12.       }  
  13.    }  
  14. public function add()  
  15. {  
  16.    $post = new Post;  
  17.    $post->setAttribute('name''Another Post');  
  18.    $post->setAttribute('user_id''1');  
  19.    $post->save();  
  20. }  
  21. public function delete()  
  22. {  
  23.    $post = Post::find(1);  
  24.    $post->delete();  

You also need to add the associated routes which we have discussed earlier.

  1. Route::get('search/query''SearchController@query');  
  2. Route::get('search/add''SearchController@add');  
  3. Route::get('search/delete''SearchController@delete'); 

Now, let’s try to dissect the whole code into small chunks and try to understand how each function works. It will give you a better understanding of what you’re trying to achieve.

First of all, try to understand the query method. It will give you an idea of how the search functionality works in Algolia.

  1. public function query()  
  2.    {  
  3.       $posts = Post::search('title')->get();  
  4.       foreach ($posts as $post) {  
  5.       // ...  
  6.    }  

Recall that we made the use of Searchable trait for making the Post model searchable. Therefore, through the post, you can easily search for any data. In the above code, one is trying to explore the data for “title” keyword.

Secondly, analyze in detail about the add method. It adds a new record.

  1. public function add()  
  2. {  
  3.    $post = new Post;  
  4.    $post->setAttribute('name''Another Post');  
  5.    $post->setAttribute('user_id''1');  
  6.    $post->save();  

There’s nothing new in the code. It’s just that Laravel will now index any new record created in Algolia library. It is what we call real-time indexing.

Lastly, there’s a delete method.

  1. public function delete()  
  2. {  
  3.    $post = Post::find(1);  
  4.    $post->delete();  

Here, the record will be removed from the Algolia index as soon as it’s deleted from the database. No need for complex logic or extra effort. The Scout library will handle everything.

Conclusion

Nowadays there’s a lot of demand for full-text search on the content-rich website. Implementing that with the custom coding is a typical task.

Taking this into account, here we have provided a step-by-step guide on setting up a Full-Text Search in Laravel using the Scout library.

#s3gt_translate_tooltip_mini { display: none !important; }