I have two models that are interconnected. I am trying to search the Products and show only the actual search results instead of ALL products in the category in which the product was found. I DO NOT want to search for any categories, as the categories will ALWAYS be displayed regardless of what they were looking for, and regardless of what was found.
Example. I have the following categories: - Food - Drinks - Candy My "Food" category has the following products: - Strawberry - Apple - Banana My "Drinks" category has the following products: - Banana Cocktail - Beer - Cola My "Candy" category has the following products: - Strawberry Lollipop - Chocolate Bar - Banana Ice Cream
So, I want to achieve the following. I am doing a product search called "Banana". I want to show:
Category Food - Product Banana Category Drinks - Product Banana Cocktail Category Candy - Product Banana Ice Cream
But my problem is in my code, if I search for "Banana", it displays the category in which the banana is found, and it returns and displays ALL products of this category instead of ONLY the products I was looking for. How can I achieve this, only those products are found that are found?
Model Categories:
class Categories extends Eloquent { public function products() { return $this->hasMany('Products'); } }
Products Model:
class Products extends Eloquent { public function categories() { return $this->belongsTo('Categories'); } }
My controller:
$searchString = Input::get('search'); if($searchString) { $categories = Categories::with('products')->orderBy($order, $by)->whereHas('products', function ($query) use ($searchString){ $query->where('name', 'like', '%'.$searchString.'%'); })->get(); } else { $categories = Categories::with('products')->orderBy($order, $by)->get(); }
My view:
@foreach($categories as $category) {{ $category->name }} // Show the category name @foreach($category->products as $product) {{ $product->name }} // Show all products in that category @endforeach @endforeach
php search laravel relation
Hardist
source share