Boost Laravel Performance: Replace Slow LIKE '%keyword%' Queries with Full-Text Search

Boost Laravel Performance: Replace Slow LIKE '%keyword%' Queries with Full-Text Search
When building search features in Laravel applications, it's common to reach for the LIKE operator:

DB::table('posts')->where('title', 'LIKE', '%Laravel%')->get(); 

However, this approach—especially with wildcards on both sides (%Laravel%)—can severely degrade performance on large datasets, because it disables index usage in most databases. 

In this article, we’ll explore efficient alternatives to %LIKE% in Laravel: 

- ✅ Using LIKE 'keyword%' for indexed searches
- ✅ Using MySQL's FULLTEXT indexing
- ✅ Bonus: Laravel Scout for powerful, scalable search 

🧠 Why %LIKE% is Slow: 

Using %keyword% forces the database to scan every row, which:
 - Ignores indexes
 - Consumes more memory and CPU
 - Slows down significantly with large tables 

Option 1: Use LIKE 'keyword%' for Indexed Searches:

If your use case only requires searching from the start of a string, use: 

DB::table('posts')->where('title', 'LIKE', 'Laravel%')->get(); 

This allows MySQL to use indexes, making the search much faster. It's ideal for autocomplete or prefix-based searches. 

🔍 Option 2: Full-Text Search with MySQL:

If you need to search within a string efficiently, consider FULLTEXT indexing. 

✅ Step 1: Add a FULLTEXT Index 

In your migration: 

Schema::table('posts', function (Blueprint $table) {
         $table->fullText(['title', 'body']);
     }); 

✅ Step 2: Search with MATCH ... AGAINST 

$results = DB::table('posts')
         ->whereRaw("MATCH(title, body) AGAINST (? IN BOOLEAN MODE)", [$searchTerm])
         ->get(); 

This is significantly faster and more powerful than LIKE, especially for multi-word or fuzzy search. 

📦 Option 3: Make it Reusable with a Model Scope

Add a scope to your Eloquent model: 

// Post.php
     public function scopeFullTextSearch($query, $term)
     {
         return $query->whereRaw("MATCH(title, body) AGAINST (? IN BOOLEAN MODE)", [$term]);
     } 

Then use it like this: 

$posts = Post::fullTextSearch('laravel eloquent')->get(); 

🚀 Bonus: Use Laravel Scout for Scalable Search

For even more robust solutions (fuzzy search, ranking, typo tolerance), Laravel Scout with services like Meilisearch or Algolia is a great option. 

composer require laravel/scout
php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider" 

Then add the Searchable trait to your model: 

use Laravel\Scout\Searchable; 

class Post extends Model { use Searchable; }

Scout handles indexing automatically and gives you powerful search capabilities out of the box. 



Comments

Leave a Comment

No comments yet. Be the first to comment!