Laravel - Query Model if values contain a certain string (taken from search input)

Laravel - Query Model if values contain a certain string (taken from search input)

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Query Model if values contain a certain string (taken from search input)

When building a search interface for an e-commerce platform, the most common stumbling block is handling partial matches across a deeply nested relationship tree. In your specific scenario, you have a Product model that belongs to a Tag and a Subcategory, while the Subcategory in turn belongs to a Category. The goal is to check if the search string exists within the names or descriptions of all these related models, not just the immediate product name.

The syntax you currently have:

$products = Product::where('name_en', 'LIKE', $search)->get();

is fundamentally correct for a single-column partial match. However, it fails to address the core requirement: querying related tables. The LIKE operator is indeed necessary here because standard equality checks (=) only trigger if the database value matches the input string exactly. If your search input is "wireless" but the database value is "wireless headphones," an equality check will miss this result. With LIKE, you typically use the % wildcard to indicate that any characters can exist before or after the search term.

To extend this logic to relationships, you must utilize Eloquent's orWhereHas method combined with a nested scope or query builder condition. Since you need to check properties of Tag, Subcategory, and Category, you cannot simply chain whereHas clauses together without defining the specific column constraints for each relationship.

Here is how you can construct the query to search across all related fields:

$searchTerm = "%{$search}%"; // Escape wildcards if necessary, or use DB::raw for safety

$products = Product::query()
    ->where('name_en', 'LIKE', $searchTerm)
    
    // Check Tag properties
    ->orWhereHas('tag', function ($query) use ($searchTerm) {
        $query->whereColumn('tags.name_en', 'LIKE', $searchTerm);
    })
    
    // Check Subcategory properties
    ->orWhereHas('subcategory', function ($query) use ($searchTerm) {
        $query->whereColumn('subcategories.name_en', 'LIKE', $searchTerm);
    })
    
    // Check Category properties (nested relationship)
    ->orWhereHas('subcategory.category', function ($query) use ($searchTerm) {
        $query->whereColumn('categories.name_en', 'LIKE', $searchTerm);
    })
    
    // Optional: Search within product description or other text fields
    ->orWhere('description', 'LIKE', $searchTerm)
    ->get();

This approach uses orWhereHas to tell Eloquent that a product should be returned if any of the specified relationships contain a matching record. The closure passed to each method allows you to scope the query specifically to that relationship's table, ensuring you check the correct columns (name_en, description, etc.) for the Tag, Subcategory, and Category tables respectively.

Performance Considerations

While this solution is functionally correct, it introduces a significant performance trade-off. Every time an Ajax request hits the search endpoint, the database executes four separate queries (one for each condition) per product table scan if indexes are not perfectly tuned. This is known as an N+1 problem in a query context, though technically these are combined into one SQL statement with multiple OR conditions.

If your dataset grows beyond a few thousand products, this pattern will degrade rapidly. The database optimizer may struggle to find the most efficient execution plan when joining three different tables just for a text match. In such cases, you should consider creating full-text indexes on these columns or implementing a dedicated search engine like Elasticsearch or Meilisearch, which are optimized for fuzzy string matching and partial containment across multiple fields simultaneously.

Additionally, always ensure that name_en and similar text columns in the tags, subcategories, and categories tables have a standard index (B-tree) on them. Without these indexes, every search will force a full table scan of the related tables, negating any benefit of your relationship queries.

Security Note

When using user input directly in LIKE clauses, be wary of SQL injection if you do not use parameter binding. In the code snippet above, we assume $search is sanitized or passed as a bound parameter. Laravel's query builder handles this automatically when you pass raw strings to methods like where, but always validate and sanitize user input before passing it into your search logic to prevent malicious payloads from breaking your application or leaking data.

Our network