Back to Blog

Typesense with Laravel Scout: A Beginner’s Guide

Introduction In modern web applications, search functionality plays a crucial role in enhancing user experience. Laravel Scout provides a simple, driver-based solution for full-text search, and when combined with Typesense, it delivers lightning-fast search capabilities. This guide will walk you through the basics of integrating Typesense with Laravel Scout to implement real-time search functionality. 1. […]

Typesense with Laravel Scout: A Beginner’s Guide

Introduction

In modern web applications, search functionality plays a crucial role in enhancing user experience. Laravel Scout provides a simple, driver-based solution for full-text search, and when combined with Typesense, it delivers lightning-fast search capabilities. This guide will walk you through the basics of integrating Typesense with Laravel Scout to implement real-time search functionality.


1. What is Laravel Scout?

Laravel Scout is an official Laravel package that provides a simple and easy-to-use driver-based solution for full-text searching. It allows you to sync your Eloquent models with search engines like Typesense, Algolia, MeiliSearch, and Elasticsearch without much hassle.

Key Features of Laravel Scout:

  • Seamless integration with Eloquent models
  • Supports multiple search drivers
  • Full-text search capabilities
  • Easy-to-use API for indexing and searching
  • Supports pagination, filtering, and highlighting

2. Basic Overview of Typesense

Typesense is an open-source, lightning-fast search engine optimized for speed and ease of use. Unlike Algolia or Elasticsearch, it is self-hosted, meaning you have full control over your data without vendor lock-in.

Why Use Typesense?

Blazing-fast performance (sub-50ms search response time)
Easy to set up and self-host
No complex configurations
Supports typo-tolerant and fuzzy search
Open-source with no hidden costs


3. Why Choose Typesense Instead of Algolia?

While Algolia is a great hosted search service, it has limitations, especially in cost and data privacy. Here’s a comparison:

Feature Typesense Algolia
Cost Free & Open-source Expensive after free tier
Hosting Self-hosted Cloud-hosted only
API Requests Unlimited Limited in pricing tiers
Data Privacy Full control Data stored on Algolia servers
Speed Sub-50ms Fast but depends on pricing
Ease of Use Simple setup Complex pricing model

If you want a free, open-source, and high-performance search engine, Typesense is a fantastic alternative to Algolia.


4. Basic Setup of Typesense and Laravel Scout

Step 1: Install Laravel Scout

Run the following command to install Laravel Scout:

composer require laravel/scout

Step 2: Install Typesense Driver

composer require typesense/typesense-laravel-scout

Step 3: Publish Scout Configuration

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

Step 4: Set Up Typesense

Download and install Typesense on your server:

curl -O https://dl.typesense.org/releases/0.24.1/typesense-server-0.24.1-linux-amd64.tar.gz

Then start the Typesense server:

./typesense-server --data-dir=/path/to/data --api-key=xyz123

Set up the .env file for Laravel Scout:

SCOUT_DRIVER=typesense
TYPESENSE_HOST=127.0.0.1
TYPESENSE_PORT=8108
TYPESENSE_API_KEY=xyz123

5. Using Typesense Search with Laravel Eloquent Models

To make an Eloquent model searchable, use the Searchable trait:

use Laravel\Scout\Searchable;

class Product extends Model
{
    use Searchable;

    public function toSearchableArray()
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'description' => $this->description,
        ];
    }
}

6. Apply Pagination to Search Results

Use Laravel’s paginate() method with Scout:

$results = Product::search('keyword')->paginate(10);

7. Highlight Search Text in Results

Typesense provides the highlight_fields feature to highlight search terms in the results. Here’s how to implement it in Laravel Scout:

$results = Product::search('keyword')
    ->withHighlight(['name', 'description'])
    ->get();

foreach ($results as $result) {
    $highlightedName = $result->getHighlight('name');
    $highlightedDescription = $result->getHighlight('description');

    echo $highlightedName ?: $result->name;
    echo "<br>";
    echo $highlightedDescription ?: $result->description;
}

Explanation:

  • withHighlight(['name', 'description']): Specifies the fields where highlighting should be applied.
  • $result->getHighlight('field_name'): Retrieves the highlighted version of the text.

8. Handling Large Data Efficiently

For large databases, use chunking when importing data:

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

Or use batching in the model:

Product::searchable()->chunk(500, function ($products) {
    $products->searchable();
});

9. Laravel Scout Commands Explained

Command Description
scout:import Imports all model data into the search engine
scout:flush Removes all indexed data from the search engine
scout:sync-index-settings Syncs index settings with Typesense
scout:delete-all Deletes all indexes

10. Configuring Laravel Scout for Typesense

Update config/scout.php with:

'driver' => env('SCOUT_DRIVER', 'typesense'),
'typesense' => [
    'api_key' => env('TYPESENSE_API_KEY'),
    'host' => env('TYPESENSE_HOST'),
    'port' => env('TYPESENSE_PORT'),
    'protocol' => 'http',
],

Major Parameters Explained:

  • api_key: Secure key for accessing Typesense
  • host: IP or domain of the Typesense server
  • port: Default is 8108
  • protocol: HTTP or HTTPS

11. Extra Important Details

Multi-Tenant Search: If your app has multi-tenancy, you can use separate Typesense indexes per tenant.
Faceted Search: Use facet_by in queries for advanced filtering.
Instant Search: Combine with Vue.js or Livewire for real-time search experience.