Learn how to use the TNTSearch driver with Laravel Scout

Published on by

Learn how to use the TNTSearch driver with Laravel Scout image

Laravel Scout provides a simple, driver-based solution for adding full-text search to your Eloquent models.

Out of the box, Laravel 5.3 ships with Algolia driver. However, we can easily write custom drivers; that’s exactly what TeamTnt has done by providing a TNTSearch driver for Laravel Scout.

Getting started

First thing, let’s install a fresh copy of Laravel 5.3, I am using the Laravel installer, hence:

laravel new scout-tntsearch

Now let’s install the required packages for running Scout and TntSearch. First install Laravel Scout:

composer require laravel/scout

Then, install the TNTSearch Driver

composer require teamtnt/laravel-scout-tntsearch-driver

Next, we’ll add the ScoutServiceProvider and the TNTSearchScoutServiceProvider to our providers array in config/app.php

'providers' => [
/*
* Package Service Providers...
*/
Laravel\Scout\ScoutServiceProvider::class,
TeamTNT\Scout\TNTSearchScoutServiceProvider::class,
]

Now, let’s publish Laravel Scout config file:

php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"

A new config file scout.php should be available in our config directory. Let’s set the config correctly so that Scout knows that we want to use TntSearch driver instead of Algolia.

In our .env file we’ll add the following:

SCOUT_DRIVER=tntsearch

Next, in config/scout.php we’ll add this:

'tntsearch' => [
'storage' => storage_path(),
],

This essentially specifies the directory where the index files will be stored.

We have now successfully configured our app with Laravel Scout and TNTSearch driver and we are ready to start searching our Eloquent Models.

Creating the database

Our App database doesn’t contain any data for the moment and we will need an actual database to test our application. So let’s grab the sample Sakila film database from MySQL that is a sample database intended to provide a standard schema that can be used for examples. Then import it into our app’s database.

Now we have some data to test out some of the features of Laravel Scout. Let’s make an Eloquent Model for the film table.

php artisan make:model Models/Film

We’ll set the primaryKey and table attribute on our Model so that Eloquent knows what to use for these values.

We now have an Eloquent Model for our film table, let’s see if we can query some data with it.

Our film table contains 1000 records, thus a perfect place to start testing the capabilities of Laravel Scout and TntSearch.

Model Indexes

From the Laravel documentation, we read the following: “Each Eloquent model is synced with a given search “index”, which contains all of the searchable records for that model. In other words, you can think of each index like a MySQL table. By default, each model will be persisted to an index matching the model’s typical “table” name. Typically, this is the plural form of the model name; however, you are free to customize the model’s index by overriding the searchableAs method on the model:”

Ok, so first will add the Searchable trait on our Model, then we will customize the index name that will be created and saved. This index will be used to perform searches instead of querying the database, hence we gain much more speed while doing searches.

Indexing

We will first need to create the Index file for the first time.

php artisan scout:import "App\Models\Film"

We can clearly notice here how Laravel Scout chunks the data and imports it in the index 100 rows at a time, hence preventing our script from crashing or timing out. That’s pretty cool if you ask me !!.

We now have in our storage directory a films_index.index file which Laravel Scout will use when performing searches on the Film Model.

Now you might be asking yourself well what happens when I update my film table, do I need to import the data again and recreate the Index. Well no, Laravel Scout already takes care of updating the Index whenever you are updating your Model. i.e when you are creating new records, updating records and deleting records.

Searching with TNT Search

We can now search our Model using the search method provided by the Searchable trait.

App\Models\Film::search('ANGELS LIFE')->get();

We get 3 results, all of which contains in their title, some of the keywords we have specified to our search method. Say goodbye to WHERE LIKE %% queries.

Also notice that all the fields that were indexed will be used during the search hence description, release_year and so on.

The speed at which these results are returned is simply amazing, and therefore will really boost your Application when you have large sets of data to search.

Final words

I would really recommend using Laravel Scout for querying large databases, this will be where it will be at it’s most useful and powerful. Make sure you also have a look through the Laravel Scout official Documentation, there is some pretty cool stuff to learn over there.

I have also published the code for this demo to GitHub, check it out for some reference.

Percy Mamedy photo

Just a guy who loves Laravel and VueJs...

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate logo

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate

Build your SaaS application in hours. Out-of-the-box multi-tenancy and seamless Stripe integration. Supports subscriptions and one-time purchases, allowing you to focus on building and creating without repetitive setup tasks.

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Asymmetric Property Visibility in PHP 8.4 image

Asymmetric Property Visibility in PHP 8.4

Read article
Access Laravel Pulse Data as a JSON API image

Access Laravel Pulse Data as a JSON API

Read article
Laravel Forge adds Statamic Integration image

Laravel Forge adds Statamic Integration

Read article
Transform Data into Type-safe DTOs with this PHP Package image

Transform Data into Type-safe DTOs with this PHP Package

Read article
PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell image

PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell

Read article
Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3 image

Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3

Read article