jeudi 13 août 2020

Larevel Eloquent with() location search

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.

It seems to return every user of every tipe where obj values are null if there is no record for that model and user,its ads the distance to the location correctly but isn't filtering by distance, don't know why.

But what I want is only users with a techer profile (teacher model) and a location within 15 miles.

The function in my model

 public function searchLocationsByDistance($query, $lat, $lng, $max_distance = 15){
    $query->getQuery()->locations = [];
    return $query->select('*')
                 ->selectRaw("( 3959 * acos( cos( radians($lat) ) * cos( radians( lat ) )  * cos( radians( lng ) - radians($lng) ) + sin( radians($lat) ) * sin(radians(lat)) ) ) AS distance")
                 ->having('distance', '<=', $max_distance)
                 ->orderBy('distance');

}

The Function in my controller

  public function search(Request $request){

$input = $request->all();
//Just google api search this populates fine.
$location =  $this->geolocatePostcode( $input['postal_code'] ); 

$instructors=\App\User::with(['teacher', 'teacher.class','teacher.location' => function ($query) 
use($location) {
    $locations = new Location;
    $locations->searchLocationsByDistance($query,$location->lat,$location->lng);
    }])
    //->where('type', '==', 'instructor')
    ->get();

   // var_dump($instructors);
    return response()->json($instructors->toArray());

}

Can anyone advise what is wrong with my queries or guide me in the right direction.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire