Database & Search8 min read

How to Use Elasticsearch with Laravel for Advanced Search

Md Shahed Alam
Md Shahed Alam
February 18, 2025
How to Use Elasticsearch with Laravel for Advanced Search

MySQL full-text search is convenient and built-in, but it has limits. It struggles with typos, relevance ranking, and scale. Elasticsearch is purpose-built for search — it handles all of these things well.

When to add Elasticsearch

Add it when users need to search across large datasets, when you need fuzzy matching and autocomplete, or when search relevance matters to your product. Do not add it for a simple search box that queries 500 rows.

Setting up with Laravel Scout

The cleanest way to integrate Elasticsearch with Laravel is through Laravel Scout with the laravel-scout-elastic driver:

composer require laravel/scout
composer require matchish/laravel-scout-elasticsearch

Add the Searchable trait to your model:

use LaravelScoutSearchable;

class Product extends Model {
    use Searchable;

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

Searching

// Simple search
$products = Product::search('wireless headphones')->get();

// With filters
$products = Product::search('headphones')
    ->where('category_id', 5)
    ->paginate(20);

Keeping the index in sync

Scout automatically indexes records when they are created or updated (if you queue the updates). For large datasets, use the import command to bulk-index:

php artisan scout:import "AppModelsProduct"

Custom mappings

For fine-grained control over how Elasticsearch handles your data — language analyzers, custom tokenizers, boosting specific fields — you will need to define custom mappings. This is where Elasticsearch gets powerful but also more complex.

Start with Scout and the default settings. Add custom mappings when you need them.

DatabaseSearch

Ready to build something great?

Let's talk about your project. We will give you honest advice, a clear plan, and a fair price. No pressure, no sales pitch.