Reputation: 443
I am using Laravel 5 and have come into a difficult problem regarding radius and zip code selection.
I have a Hotel model and a large Database of hotels. Each hotel in my DB has a Lat/Lng and also a Radius (in miles) of how far they accept customers from. Most of these Hotels have a radius of 50, but some are higher or lower.
Users on my website enter a zipcode for their search. I use this zipcode to return a Lat/Lng and then query all hotels within X miles from them. I am currently using this code:
$lat = '123'; // geocoded from user entered zip
$lng = '123'; // geocoded from user entered zip
$radius = '50'; // currently, hardcoded, need to change
$hotels = Hotel::select(
\DB::raw("*,
( 3959 * acos( cos( radians(" . $lat . ") ) *
cos( radians( lat ) )
* cos( radians( lng ) - radians(" . $lng . ")
) + sin( radians(" . $lat . ") ) *
sin( radians( lat ) ) )
) AS distance"))
->having("distance", "<", $radius)
->orderBy("distance")
->get();
As you can see above, I am currently hard coding "50" as the radius but really what I need to do is to use the 'radius' column in the Hotel table.
What is the best way to accomplish this?
Upvotes: 0
Views: 1439
Reputation: 33068
You should just need to compare the calculated distance to the number in the radius column (or what you are calling the radius column in the hotels table.
Try swapping out your having
clause with this havingRaw
. You will need to change radius
to the name of the column in your table which stores the hotel's radius. It's probably also better to use less than or equals as well.
->havingRaw("distance <= radius")
Upvotes: 0