title: Eloquent query using join to retrieve pivot table and related data
body: <p>In my controller I have a query like this:</p>
  
  <pre><code>$userinfos = User::with('skills');
  $userinfos-&gt;with('positions');
  $userinfos=$userinfos-&gt;get();
  </code></pre>
  
  <p>And that works fine, in my view, I get the position name like this:</p>
  
  <pre><code>@forelse ($userinfos[0]-&gt;positions as $key=&gt;$position)
      {{ $position-&gt;name}}
  @empty
      No position listed
  @endforelse 
  </code></pre>
  
  <p>I have another like this to retrieve related company data:</p>
  
  <pre><code>$positions = \DB::table('positions')
  -&gt;select(\DB::raw('position_user.id as id, positions.id as position_id, positions.name as position_name, companies.id as company_id, companies.name as company_name, position_user.user_id'))
  -&gt;join('position_user','position_user.position_id','=','positions.id')
  -&gt;join('companies','companies.id','=','position_user.company_id')
  -&gt;join('users','users.id','=','position_user.user_id')
  -&gt;where('position_user.user_id',$userid)
  -&gt;get();
  </code></pre>
  
  <p>And that also works fine to get the positions and company name:</p>
  
  <pre><code>@forelse($positions as $key=&gt;$position)
      {{$position-&gt;position_name}} @ {{$position-&gt;company_name}}
  @empty
      No position listed
  @endforelse
  </code></pre>
  
  <p>I am sure there must be a way to combine the two so that I can get the company name in the first query. I am looking for something like this:</p>
  
  <pre><code>$userinfos = User::with('skills');
  $userinfos-&gt;with('positions');
  $userinfos-&gt;whereHas('positions', function($thisQuery) 
  {
      $thisQuery-&gt;join('companies','companies.id','=','position_user.company_id');
  });
  
  $userinfos=$userinfos-&gt;get();
  </code></pre>
  
  <p>Is that even possible? Any ideas/direction would be greatly appreciated!</p>
  
  <p>EDIT:</p>
  
  <p>Should I perhaps be looking at adding in a join to my Position class to enable the above:</p>
  
  <pre><code>public function users()
  {
      return $this-&gt;belongsToMany('App\User')-&gt;withTimestamps()
      -&gt;withPivot('company_id');
      -&gt;join('companies','companies.id','=','position_user.company_id');
  }
  </code></pre>
  
  <p>If so - how would I access that in the view? </p>