peterlee's avatar

Is there any efficient way to calculate distance using eloquent ?

What I am trying to do is calculate physical distance from user's location to a restaurant that has coordinate in database so database table has two column, latitude and longitude.

and user's location will be given by using

$userLatitude = $request['user_latitude']
$userLongitude = $request['user_longitude'];

so distance between a user and a restaurant will be

distance = function(user's location,  restaurant's location)

and that mathmatical formular is quite complecate and it would intensly slow the query down in order to fetch data if I use customized method in mySQL.

and as distance filter will be used in pagination and front-end.

it would be great to include distance column in newly fetched data from query in order to use orderby('distance') in eloquent.

Could you recommend any effective way ?

0 likes
6 replies
Mittensoff's avatar

Why don't you just do the calculation in a Controller and order the array by using a php/Laravel function?

You need a separate table (assuming that the user location is dynamic) if you explicitely want to fetch the data

1 like
peterlee's avatar

@Mittensoff Well.. Using php/laravel function would be useful only if I fetch all the data from table at once but I will use a pagination for fetching data, so when end-user scroll down as I use a list in application, data will be newly fetched.

so distance would not be ordered in that way.

peterlee's avatar

@cviv

Thank you for your reply

but this question is not about formula

spekkionu's avatar
Level 48

You will need the calculation part of the query to use DB::raw().

You might even want to just use a plain query and hydrate the results into models afterward (or just leave them as plain arrays).

Keep in mind that the calculations can be slow so it might be a good idea to cache the results.

Please or to participate in this conversation.