Please help me convert this SQL into an eloquent query

Posted 1 year ago by rammy85

I am trying out a way to conduct a spatial query in eloquent so I can return user models to pass to a view. the aim is search by distance in order of distance. I have this raw query as outlined below

public static function searchByDistance($distance, $unit) {

    //spatial queries        
     
        $circle_radius = 6371;       
   
       // $circle_radius = 3959; 
  

    $max_distance = $distance;
    $lat = Auth::user()->getLoc()->latitude;
    $lng = Auth::user()->getLoc()->longitude;

    //get all nearby places
     $nearbyusers = DB::select(
           'SELECT * FROM
                (SELECT users.id, users.country, places.name, places.state_code, places.latitude, places.longitude, (' . $circle_radius . ' * acos(cos(radians(' . $lat . ')) * cos(radians(latitude)) *
                cos(radians(longitude) - radians(' . $lng . ')) +
                sin(radians(' . $lat . ')) * sin(radians(latitude))))
                AS distance
                FROM users
                LEFT JOIN places ON users.suburb=places.name) AS distances
            WHERE distance < ' . $max_distance . '
            ORDER BY distance;
     ');      

       

   $nearbyusers = (object)$nearbyusers;



    return $nearbyusers;


}

and it returns objects. Is there a way someone could please help me convert it to eloquent? Please?

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.