title: Laravel scope on collection
body: <p><strong>I'm in Pain because of this problem.</strong></p>
  <h2>Problem</h2>
  <p>I have <code>categories</code> table which contains <code>id</code>, <code>slug</code> and <code>parent_id</code>.</p>
  <p><code>lessons</code> table which contains <code>category_id</code> (the child of a <code>Category</code>)</p>
  <p>I want by Eloquent scope get all lessons posted by <code>Category</code> parent <code>id</code></p>
  <p>example:</p>
  <blockquote>
  <p>parent category of <code>id=1</code> have children categories of ids <code>3</code>, <code>4</code> and <code>5</code>.</p>
  <p>Then retrieve <code>Lesson</code>s under the parent category of <code>id=1</code>, <strong>so this must return the lessons of all of the childrens</strong>.</p>
  </blockquote>
  <p><strong>Categories table</strong></p>
  <p><a href="https://i.stack.imgur.com/wxZCc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wxZCc.png" alt="enter image description here" /></a></p>
  <pre><code>public function parent()
  {
      return $this-&gt;belongsTo(self::class, 'parent_id');
  }
  
  
  public function lessons()
  {
      return $this-&gt;hasManyThrough(
          \App\Lesson::class, \App\Category::class,
          'parent_id', 'category_id', 'id'
      );
  }
  
  //Pointless try
  // public function scopeGetParent($query, $slug)
  // {
  //  $query-&gt;where('slug', $slug)-&gt;first()-&gt;lessons;
  // }
  
  public function children()
  {
      return $this-&gt;hasMany(self::class, 'parent_id');
  }
  </code></pre>
  <p><strong>Lessons.php</strong></p>
  <pre><code>                    return Lesson::recentLessons()
                      -&gt;byParentCategory($args['category'])
                      -&gt;simplePaginate($page)
                      -&gt;shuffle();
  </code></pre>
  <p>how can I construct scopeByParentCategory() function??</p>
  <p><strong>sorry for the fuzzy question! Spent 3 hours trying :(</strong></p>
  <p><strong>update</strong>: I got this idea right after posting the question but still wanna know what do you think about it and if this the best way to handle it.</p>
  <pre><code>    public function scopeByParentCategory($query, $slug)
  {
      $ids = [];
      foreach (Category::where('slug', $slug)-&gt;first()-&gt;children as $value)
      {
          $ids[] = $value-&gt;id;    
      }
  
      return $query-&gt;whereIn('category_id', $ids);
  }
  </code></pre>