title: Laravel 5.2 | query many to many to one
body: <p>Currently I am working on a multi domain and language project where videos are reused with different titles and description.</p>
  
  <p>My tables that are relevant to this question with relations look like</p>
  
  <pre><code>posts    &gt;-    videos    &gt;-    videos_tags    -&lt;    tags
  id             id              id                   id
  domain_id                      video_id             
  video_id                       tag_id
  </code></pre>
  
  <p>Of course I have created the models: Post, Video and Tag with all the required relationships.</p>
  
  <p>The thing I am trying is to get all the posts by my Tag model and maintaining the pagination() functionality.</p>
  
  <p>I am able to get all tags linked to a Post through a Video model. However when I am trying an inverse way I don't seem to keep the pagination() functionality. I have tried a lot but can't seem to find the right solution.</p>
  
  <p>The closest (I think) I have been with this piece of code:</p>
  
  <pre><code>// App\Models\Tag
  public function posts()
  {
      $posts = [];
  
      foreach ($this-&gt;videos as $video)
      {
          foreach ($video-&gt;posts as $post)
          {
              if (!array_key_exists($post-&gt;id, $posts)) $posts[$post-&gt;id] = $post;
          }
      }
  
  
      return \Illuminate\Database\Eloquent\Collection::make($posts);
  }
  </code></pre>
  
  <p>Any suggestions or articles I have missed during my quest for the answer are welcome :)</p>