現在、私は中古品のプラットフォームで作業しており、laravelで作業しています。larvelプロジェクトで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