title: Laravel Eloquent with() location search
body: <p>I'm trying to return a list of Users of type teacher who have an associated teacher profile, their associated class and location who are within 15 miles of a postcode.</p>
  <p>It seems to return every user of every type where obj values are null if there is no record for that model and user,its adds the distance to the location correctly but isn't filtering by distance, don't know why.</p>
  <p>But what I want is only users with a teacher profile (teacher model) and a location within 15 miles.</p>
  <p>The function in my model</p>
  <pre><code> public function searchLocationsByDistance($query, $lat, $lng, $max_distance = 15){
      $query-&gt;getQuery()-&gt;locations = [];
      return $query-&gt;select('*')
                   -&gt;selectRaw(&quot;( 3959 * acos( cos( radians($lat) ) * cos( radians( lat ) )  * cos( radians( lng ) - radians($lng) ) + sin( radians($lat) ) * sin(radians(lat)) ) ) AS distance&quot;)
                   -&gt;having('distance', '&lt;=', $max_distance)
                   -&gt;orderBy('distance');
  
  }
  </code></pre>
  <p>The Function in my controller</p>
  <pre><code>  public function search(Request $request){
  
  $input = $request-&gt;all();
  //Just google api search this populates fine.
  $location =  $this-&gt;geolocatePostcode( $input['postal_code'] ); 
  
  $instructors=\App\User::with(['teacher', 'teacher.class','teacher.location' =&gt; function ($query) 
  use($location) {
      $locations = new Location;
      $locations-&gt;searchLocationsByDistance($query,$location-&gt;lat,$location-&gt;lng);
      }])
      //-&gt;where('type', '==', 'instructor')
      -&gt;get();
  
     // var_dump($instructors);
      return response()-&gt;json($instructors-&gt;toArray());
  
  }
  </code></pre>
  <p>Can anyone advise what is wrong with my queries or guide me in the right direction.</p>