title: Laravel Search Relationship
body: <p>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 product was found. I DO NOT want to search for any categories, since the categories will ALWAYS be displayed no matter what was searched for and no matter what was found.</p>
  
  <pre><code>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
  </code></pre>
  
  <p>So, what I WANT to achieve is the following. I do a search for a product called "Banana". What I WANT to be displayed is:</p>
  
  <pre><code>Category Food
  - Product Banana
  
  Category Drinks
  - Product Banana Cocktail
  
  Category Candy
  - Product Banana Ice Cream
  </code></pre>
  
  <p>But my issue is, with my code, if I perform a search for "Banana", it displays the category in which banana is found, and it returns and displays ALL products in that category instead of ONLY the products that I searched for. How can I achieve it so only the products that was searched for are displayed?</p>
  
  <p>Categories Model:</p>
  
  <pre><code>class Categories extends Eloquent {
  
      public function products()
      {
          return $this-&gt;hasMany('Products');
      } 
  }
  </code></pre>
  
  <p>Products Model:</p>
  
  <pre><code>class Products extends Eloquent {
  
      public function categories()
      {
          return $this-&gt;belongsTo('Categories');
      }
  }
  </code></pre>
  
  <p>My Controller:</p>
  
  <pre><code>    $searchString       = Input::get('search');
  
      if($searchString)
      {
          $categories = Categories::with('products')-&gt;orderBy($order, $by)-&gt;whereHas('products', function ($query) use ($searchString){
              $query-&gt;where('name', 'like', '%'.$searchString.'%');
          })-&gt;get();
      }
      else {
          $categories     = Categories::with('products')-&gt;orderBy($order, $by)-&gt;get();
      }
  </code></pre>
  
  <p>My View:</p>
  
  <pre><code>@foreach($categories as $category)
      {{ $category-&gt;name }} // Show the category name
  
      @foreach($category-&gt;products as $product)
      {{ $product-&gt;name }} // Show all products in that category
  
      @endforeach
  @endforeach
  </code></pre>