Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

gaan10's avatar

Want to convert sql query to laravel

I have this sql query which is working fine. I wanted to convert this to laravel,which i am not able to make it working. plz help.

SELECT
  id, (
    6371* acos (
      cos ( radians(12.9166) )
      * cos( radians( lat ) )
      * cos( radians( lon ) - radians(77.6101) )
      + sin ( radians(12.9166) )
      * sin( radians( lat ) )
    )
  ) AS distance
FROM doctors
HAVING distance < 5
ORDER BY distance
LIMIT 0 , 20;
0 likes
6 replies
Neven's avatar

Something like that ?

$lat = $request->lat;
$lon = $request->lon;
$formula = 6371* acos ( cos ( radians(12.9166) ) * cos( radians( $lat ) ) * cos( radians( $lon ) - radians(77.6101) ) + sin ( radians(12.9166) ) * sin( radians( $lat ) );

$doctors = Doctor::whereraw($formula,'<', 5)->orderBy('distance')->pluck('id')->limit(20);

im not sure

realrandyallen's avatar
Level 44

I'd use a selectRaw statement, something like this:

$data = Doctor::selectRaw('(
          6371* acos (
            cos ( radians(12.9166) )
            * cos( radians( lat ) )
            * cos( radians( long ) - radians(77.6101) )
            + sin ( radians(12.9166) )
            * sin( radians( lat ) )
          )
        ) AS distance')
    ->having('distance', '<', '5')
    ->orderBy('distance')
    ->limit(20)
    ->get();

https://laravel.com/docs/master/queries#raw-expressions

gaan10's avatar

@realrandyallen This works but when i replace the nos with requested latitude and longitude.It shows unexpected error inputs not found.How to provide the user input lat and lon. I wrote this but not working :

    $inputs = \Input::all();
      
    $datas = Doctor::selectRaw('(
          6371* acos (
            cos ( radians('$inputs['lat']') )
            * cos( radians( lat ) )
            * cos( radians( lon ) - radians('$inputs['lon']') )
            + sin ( radians('$inputs['lat']') )
            * sin( radians( lat ) )
          )
        ) AS distance')
    ->having('distance', '<', '5')
    ->orderBy('distance')
    ->limit(20)
    ->get();
gaan10's avatar

ok got the clue where i was passing it wrongly .It should be ' . $lat . ' instead of ' $inputs['lat'] '. Thanks @snapey for the hint.

Snapey's avatar

Be very careful about creating sql injection weakness. If you are concatenating the lat and long into the search string, make sure you validate that they are only numbers and cannot be used to inject sql.

Please or to participate in this conversation.