title: Using eloquent select related entries after restricting parent entry in Laravel
body: <p>If I have a laravel class, say Category, which has a 1:many relationship with another class, say Subcategory, How do I query <em>all</em> subcategories, with restrictions on the Category class?</p>
  
  <p>For example, Query ALL subcategories where the Category class has the title "TEST".</p>
  
  <pre><code>class Category extends Model
  {
      public function subcategories()
      {
          return $this-&gt;hasMany('App\Subcategory');
      }
  }
  
  class Subcategory extends Model {
      public function category(){
          return $this-&gt;belongsTo('App\Category');
      }
  }
  </code></pre>
  
  <p>I've tried <a href="http://laravel.com/docs/5.0/eloquent" rel="nofollow">eager loading</a> via:</p>
  
  <pre><code>    $subcategories = Subcategory::with(['category' =&gt; function($query)
          {
              $query-&gt;where('title', '=', 'TEST');
  
          }])-&gt;get();
  
  // Returns ALL subcategories, with null where the category doesn't = TEST
  </code></pre>
  
  <p>I am interested in all methods of doing this!</p>
  
  <p>edit -- Two solutions:</p>
  
  <pre><code>$data = Category::whereTitle('TEST')-&gt;first()-&gt;subcategories
  //or equivalently:
  $data = Category::whereTitle('TEST')-&gt;get()[0]-&gt;subcategories;
  </code></pre>
  
  <p>or within subcategory create a dynamic scope using @The Alpha's solution</p>
  
  <pre><code>public function scopeFromCategory($query, $type)
  {
      return $query-&gt;whereHas('Category', function ($q) use ($type)
      {
          $q-&gt;whereTitle($type);
  
      });
  }
  
  // So you can later call
  $data = Subcategory::FromCategory('TEST')-&gt;get();
  </code></pre>