I have a query that searches based on a long and lat that I insert to it. Anyways the query works fine and it filters based on location, however the distance doesnt return as a variable to the collection. I believe it is because its inside the inner loop of the where. Please have a look at my code:
I need distance
to be returned as well to the main collection in $results
.
Thank you in advance.
$results = Squads::where(function ($q) use ($coordinates, $searchString, $searchGender, $searchAgeGroup) {
// SEARCH STRING
if ($searchString) {
$q->where('name', 'LIKE', "%$searchString%");
}
if ($searchGender) {
$q->where('squad_gender', '=', $searchGender);
}
// COORDINATES
if ($coordinates) {
$coordinates = explode(',', $coordinates);
$radius = 100;
$haversine = '(6371 * acos(cos(radians(' . $coordinates[0] . '))
* cos(radians(`lat`))
* cos(radians(`lng`)
- radians(' . $coordinates[1] . '))
+ sin(radians(' . $coordinates[0] . '))
* sin(radians(`lat`))))';
$q->select('id', 'country', 'address', 'lng', 'lat')
->selectRaw("{$haversine} AS distance")
->when($radius, function ($query) use ($radius, $haversine) {
return $query->whereRaw("{$haversine} < ?", [$radius]);
});
}
// $q->where('is_private', 0);
})->paginate($hasLimit ? $hasLimit : 10)->withQueryString();```
2
Answers
I wasn’t able to run your code because it is very database specific, but i think that you have got three IF branches in your code and these are overwriting the $result variable instead of adding a result to it. When the callback $q runs the overwriting happens, so maybe you should make result to an array and push the results to it.
My more general opinion to this matter is, that PHP and Laravel still misses a proper debugger, which makes finding bugs difficult.
I think you should use the laravel dd() helper, which lets you print out a variable state and then stops the program flow instantly.
So try dd(‘The value of the $result variable: ‘ , $result). Try this out.
My other opinion on this is that this code seems not clean to me, it seems to be unnecessary complicated and hard to understand. Maybe You should clean it up, make it simpler.
Try to change like this.