I was hoping someone could help me with something I'm struggling with (which is probably reasonably simple), which is searching for some products and only returning those which belong to a specific category.
My products model has this:
public function categories()
{
return $this->belongsToMany(Productcategory::class, 'products_productcategories', 'product_id', 'productcategories_id');
}
and my products productcategory model has this:
public function products()
{
return $this->belongsToMany(Product::class, 'products_productcategories', 'productcategories_id', 'product_id');
}
In the 'products_productcategories' pivot table, I have 'productcategories_id' and 'product_id' columns.
When I do my search, I'm searching for product titles which contain a keyword (a variable called searchText) as well as a category ID (which will be a variable called searchCategory). If the category ID is empty, it ignores the categories and searches for all products. That works fine:
$search_results = Product::select("*")
->orderby('created_at', 'desc')
->where('type', '!=', 'grouped')
->where('title', 'like', '%' . $searchText . '%')
->orWhere('search_terms', 'like', '%' . $searchText . '%')
->paginate(20);
What I don't understand, is how to structure my search query so that it returns the products but only if they're in the category selected by the user.
So, using the above code as a starting point, how would I adapt it to pull only products which belong to a category with an ID of (say) 6?
Any help would be appreciated!