I have two models which are related. I am trying to do a search in Products and only display the actual search results instead of ALL products of the category in which the produ
I don't know what how are you viewing the results, but I think if you just eager load the products on the categories you should be good.
$categories = Categories::whereHas('products', function ($query) use ($searchString){
$query->where('name', 'like', '%'.$searchString.'%');
})
->with(['products' => function($query) use ($searchString){
$query->where('name', 'like', '%'.$searchString.'%');
}])->get();
foreach($categories as $category){
echo $category->name . ':' . PHP_EOL;
foreach($category->products as $product){
echo . '-' . $product->name . PHP_EOL;
}
}