So I have done the following: I have a table called group that has longitude and latitude which is essentially a location of the group. Then I have an append
which calculates the distance from the user.
Group Model:
class Group extends Authenticatable
{
protected $fillable = [
'lng',
'lat'
];
protected $appends = [
'distance_from_user'
];
public function getDistanceFromUserAttribute(query) {
$ip = Request::ip();
$coordinates = \Location::get($ip);
$radius = 4000;
$latFrom = deg2rad($coordinates->latitude); // current user's lat
$lonFrom = deg2rad($coordinates->longitude); // current user's long
$latTo = deg2rad($this->lat); // this is coming from the database
$lonTo = deg2rad($this->lng); // this is coming from the database
$latDelta = $latTo - $latFrom;
$lonDelta = $lonTo - $lonFrom;
$angle = 2 * asin(sqrt(pow(sin($latDelta / 2), 2) + cos($latFrom) * cos($latTo) * pow(sin($lonDelta / 2), 2)));
return $angle * 6371;
}
}
What I want to do now is USE that distance from user
in a where clause like below in a scope, which sits in the same model as above.
Scope Inside Group Model:
public function scopeGetAllGroups($query)
{
return Groups::get()->where('distance_from_user', '<', 25);
}
But the distance_from_user
is not available at this point when I use the scope. How can i manage this so that I can use the calculated distance in a query.
Thank you in advance!