Jaad
Jaad

Reputation: 89

How do I filter certain column using Laravel Scout

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

Upvotes: 0

Views: 354

Answers (0)

Related Questions