i have a problem with a query string in Laravel 5.6
I have this two entities, ER Schema:
and related model: Note model Location model
My problem is that I have to select all notes in a certain location passing as query string parameters latitude and longitude.
A query string could be:
homestead.test/api/notes?lat=45.5432&long=43.6543&max_distance=1.1
I try to build a query Here the NoteController code, but there is a problem:
Actually the output show me every note. This is a postman output and in addition to the notes in the right location, I also return those with location = null. Going to see in the database these notes have only one parameter that coincides with those passed in query string. Theoretically it should not return them and I can not take them off in any way. could someone help me?
I hope I was clear enough, thanks in advance
Node::with(['location' => function($query) use ($latitude, $longitude){
$query->where('latitude', $latitude);
$query->where('longitude', $longitude);
}])->get()
If it can help someone, I solved the problem in this way.
public function index(Request $request) {
if($request->has('lat') &&
$request->has('long')) {
$lat1 = $request->query('lat');
$long1 = $request->query('long');
$max_distance = $request->query('max_distance');
$notes = Note::All();
foreach ($notes as $key => $value) {
if($value->location != null) {
$lat2 = $value->location->latitude;
$long2 = $value->location->longitude;
$distance = sqrt(pow($lat2-$lat1, 2) + pow($long2-$long1, 2));
if($distance > $max_distance) {
$notes->forget($key);
}
} else {
$notes->forget($key);
}
}
return $notes;
}
return Note::All();