현재 초침 제품을위한 플랫폼에서 작업 중이며 laravel로 작업 중입니다.laravel 프로젝트의 foreach 필터
최대 제품 수만 표시하고 싶습니다. 현재 사용자로부터 10km 떨어진 곳에 있습니다. 사용자 위치 및 제품 위치는 데이터베이스에 저장되며 제품을 뷰로 보내는 동일한 컨트롤러에서 이들 사이의 거리를 계산합니다.
이제 컨트롤러에 계산 된 거리에서 내 foreach를 필터링하여 거리가 10km 이상인 제품을 필터링 할 수 있는지 궁금합니다.
나는 내 코드가 그렇게 좋지 않아서 이것을 달성하기 위해 다른 옵션을 고려해야한다고 생각합니다.
컨트롤러 기능 :
이public function getNearest()
{
$products= Product::orderBy('created_at','DESC')->paginate(5);
foreach($products as $product) {
//function that calculate distance
$user = Auth::user();
$address = $product->locatie; //location of product
$prepAddr = str_replace(' ','+',$address);
$geocode=file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');
$output= json_decode($geocode);
$latitude = $output->results[0]->geometry->location->lat;
$longitude = $output->results[0]->geometry->location->lng;
$address2 = $user->locatie; //location current user
$prepAddr2 = str_replace(' ','+',$address2);
$geocode2=file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr2.'&sensor=false');
$output2= json_decode($geocode2);
$latitude2 = $output2->results[0]->geometry->location->lat;
$longitude2 = $output2->results[0]->geometry->location->lng;
$coordinate1 = new Coordinate($latitude, $longitude); //location current user
$coordinate2 = new Coordinate($latitude2, $longitude2); //location product
$calculator = new Vincenty();
$d = $calculator->getDistance($coordinate1, $coordinate2);
$distance =$d/1000;
$product->distance = round($distance);
if($product->distance>10){
//dont show product above 10km and filter foreach somehow?
}
}
return view('welcome',compact('products'));
}
보기 :
@foreach ($products as $product)
<div class="col-lg-3 margin-tb">
<img src="/uploads/products/{{ $product->afbeelding }}">
<p>{{ $product->name}}</p>
<p>{{ $product->details}}</p>
<p>{{ $product->price}}</p>
<p>{{ $product->locatie}}</p>
<p>{{ $product->distance}} km van jouw locatie</p>
<a href="/Zoekertjes/{{ $product->id }}">bekijken</a>
</div>
@endforeach