I need to grab the vehicles whose relation \'dealer\' is having distance < 200
Vehicle::join(\'dealers\', \'vehicles.dealer_id\', \'=\', \'dealers.id\')
Here's something I did that appears to be similar to what you're trying to do:
public function scopeNearest($query, Geo $geo, $miles = 25)
{
return $query
->select(DB::raw("*, ( 3959 * acos( cos( radians({$geo->lat}) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians({$geo->lng}) ) + sin( radians({$geo->lat}) ) * sin( radians( lat ) ) ) ) AS distance"))
->groupBy('id')
->having('distance', '<', $miles)
->orderBy('distance');
}
In this example, I had a separate model handling latitude and longitude coordinates, as well as address information called Geo
. You might not need that level of separation, so you can probably refactor to something like this:
public function scopeNearest($query, $lat, $lng, $miles = 25)
{
return $query
->select(DB::raw("*, ( 3959 * acos( cos( radians({$lat}) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians({$lng}) ) + sin( radians({$lat}) ) * sin( radians( latitude ) ) ) ) AS distance"))
->groupBy('id')
->having('distance', '<', $miles)
->orderBy('distance');
}
Remember, in order to calculate distance, you need two points. The model will be able to check the distance between two points by using its own latitude
and longitude
columns against the latitude and longitude provided to the scope query as an argument.
You can put this in your Vehicle model and call like so:
Vehicle::nearest($latitude, $longitude, 200);
This is untested for your use-case, so I can't guarantee that it will work out of the box, but hopefully it should point you in the right direction.