title: (Laravel Eloquent) Get posts of category and all nested subcategories
body: <p>I would like to retrieve all posts of chosen category and all nested subcategories. I mean sth like this:</p>
  
  <pre><code>[id= 1]-Category 1
  [id= 7]--Category 1.1
  [id=12]---Category 1.1.1
  [id=13]---Category 1.1.2
  [id= 9]--Category 1.2
  [id= 3]-Category 2
  </code></pre>
  
  <p>At first I tried to get recursively all IDs of chosen category and all nested subcategories and then retrieve posts with those categories IDs.</p>
  
  <p>I wrote method <code>getSubcategoriesIds($category)</code> in controller which actually give me what I want but it returns array with duplicated ids. For instans, category 1 I get:</p>
  
  <pre><code>array:10 [
      0 =&gt; 1
      1 =&gt; 7
      2 =&gt; 1
      3 =&gt; 7
      4 =&gt; 12
      5 =&gt; 1
      6 =&gt; 7
      7 =&gt; 12
      8 =&gt; 13
      9 =&gt; 9
  ]
  </code></pre>
  
  <p>How can I improve the method to return IDs without duplicates?
  Or maybe there is better way to revive those posts?</p>
  
  <p>Here are my files:</p>
  
  <p><strong>Model Category.php:</strong></p>
  
  <pre><code>class Category extends Model {
  
      public function parent() {
          return $this-&gt;belongsTo('App\Category', 'parent_id');
      }
  
      public function children() {
          return $this-&gt;hasMany('App\Category', 'parent_id');
      }
  
      public function subcategories() {
          return $this-&gt;children()-&gt;with('subcategories');
      }
  
      public function parents() {
          return $this-&gt;parent()-&gt;with('parents');
      }
  
      public function posts(){
          return $this-&gt;hasMany('App\Post');
      }
  }
  </code></pre>
  
  <p><strong>PostController.php:</strong></p>
  
  <pre><code>public function show($id)
  {
      $ids =$this-&gt;getSubcategoriesIds(Category::with('subcategories')-&gt;where('id', $id)-&gt;first()));
      $posts = Post::whereIn('category_id', $ids)-&gt;get();
      return view('post.index', compact('posts'));
  }
  
  public function getSubcategoriesIds($category) {
      $array = [$category-&gt;id];
      if(count($category-&gt;subcategories) == 0) {
          return $array;
      } 
      else  {
          foreach ($category-&gt;subcategories as $subcategory) {
              array_push($array, $subcategory-&gt;id);
              if(count($subcategory-&gt;subcategories)){
                  $array = array_merge($array, $this-&gt;getChildren($subcategory-&gt;subcategories, $array));
              }
          }
          return $array;
      }
  }
  
  public function getChildren($subcategories, $array) {
      foreach ($subcategories as $subcategory)  {
          array_push($array, $subcategory-&gt;id);
          if(count($subcategory-&gt;subcategories)){
              return $array = array_merge($array, $this-&gt;getChildren($subcategory-&gt;subcategories, $array));
          }
          return $array;
      }
  }
  </code></pre>