Search Laravel

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 
+8
php search laravel relation
source share
1 answer

I don’t know how you view the results, but I think that if you just want to download products by category, 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; } } 
+12
source share

All Articles