1

I need to fetch the data from table "properties" where I am storing the address of the property in longitude and latitude and other fields like construction_type,no_of_bedrooms,no_of_bathrooms. Now I need to filter the data according to the nearest location given with passing other filters like construction_type,no_of_bedrooms,no_of_bathrooms.

I am using Haversine formula to fetch the nearest locations by given location. I am having complexities in writing the laravel eloqent query when passing other filters as well.

$property = (new Property())->newQuery();
    if(\Request::get('Lat')!=null && \Request::get('Lng')!=null){
        $lat=\Request::get('Lat');
        $lng=\Request::get('Lng');
        $radius=200;
        $q="( 3959 * acos( cos( radians(' . $lat . ') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(' . $lng . ') ) + sin( radians(' . $lat .') ) * sin( radians(lat) ) ) )";
        $property->selectRaw("{$q} AS distance")->havingRaw("distance < ?", [$radius]);
    }

     if(\Request::get('construction_status')!=null){
         $property->where('construction_status', \Request::get('construction_status'));
     }
//other filters
return $property->get();

I expect the result as the properties with the nearest location given and other filters as well

2
  • What problem are you having? Do any of your other filters call select()?
    – patricus
    Commented Jul 18, 2019 at 3:46
  • I am having problem of writing raw sql query with $property = (new Property())->newQuery(); Commented Jul 18, 2019 at 4:16

1 Answer 1

1

Try to write your query like this

$property = \DB::table('seller_properties');
    if(\Request::get('construction_status')!="any"){
             $property->where('construction_status', \Request::get('construction_status'));
         }
    //other filters
    if(\Request::get('Lat')!="" && \Request::get('Lng')!=""){
      $lat=\Request::get('Lat');
    $lng=\Request::get('Lng');
      $haversineSQL='( 3959 * acos( cos( radians(' . $lat . ') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(' . $lng . ') ) + sin( radians(' . $lat .') ) * sin( radians(lat) ) ) )';
      // resolve haversine formula here
    $property->whereRaw($haversineSQL . '<= ?', [25]);
     }
    return $property->get();

NOTE: // dont initialize $property like this $property = (new Property())->newQuery();

1
  • 1
    Thank you .. you made my day Commented Jul 19, 2019 at 10:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.