0

Products table

id name commercial_name category_id
1 Pro1 Pro Com1 1
2 Pro2 Pro Com2 2

Categories table

id name
1 Cat 1
2 Cat 2

What I am trying to do

I am using Meilisearch with Laravel Scout and I am trying to make the user search and filter.

For example JSON get request from frontend:

{
    "query": "Com2",
    "filters": [
        {
            "category_name": "cat 2"
        }
    ]
}

This should return the product with id 2 and its assigned category.

In other words: User may search in multiple tables with relationships and filter by each table column.

Kindly know that filter should not be the exact match of the value

What I have tried

// THIS WORKS FOR NORMAL SEARCH
$query = Product::search($request->query)->paginate(30);

// THIS DOES NOT WORK
$query = Product::search($request->query)
    ->whereHas(
        'category',
        function ($query) use ($request) {
            $query->where('name', 'LIKE', '%'.$request->filters[0]['category_name'].'%');
        }
    )
    ->paginate(30);

Here I am trying to add where condition to the search query

matiaslauriti
  • 7,065
  • 4
  • 31
  • 43
Jaad
  • 89
  • 1
  • 6
  • you can try the whereHas method to filter the results based on the related model's data. – user580950 Feb 05 '23 at 22:01
  • The `Product::search()` method returns a Scout search engine, not an eloquent search builder. You cannot add eloquent or database query builder conditons like this (the `whereHas()`. You can send a query string into `Product::search()` and you can pass in some additional options which include simple filters through a callback to `Product::search()`. The callback syntax will vary with each search engine, so Mielisearch has its own way to drive it. – Jason Feb 05 '23 at 22:54

0 Answers0