I have a simple question and I didn´t find what I need.
I need to calculate the distance between t2 geocode points for a list of Stores. I also need it to be paginat
Ok, I got a solution! I don´t like it because I must to load all the rows in RAM and then use the manual paginator.
public function stores($lat, $lon){
$stores = DB::table('stores')
->selectRaw(' *, distance(lat, ?, lng, ?) as distance ')
->setBindings([$lat,$lon])
->orderBy('distance')
->get();
$result_p = new Paginator($stores, $this->limit, Request::input('page'),['path' => Request::url() ]);
return $result_p;
}
After this I was looking more inforamtion and the problem is setBindings([$lat,$lon])
The latest and Good solution:
public function stores($lat, $lon){
return $stores = DB::table('stores')
->selectRaw(" *, distance(lat, {$lat}, lng, {$lon}) as distance ")
->orderBy('distance')
->paginate($this->limit);
}
Use the selectRaw
method on the Eloquent model.
Store::selectRaw('*, distance(lat, ?, lng, ?) as distance', [$lat, $lon])
->orderBy('distance')
->paginate(10);
In that case Laravel asks the database for the amount of rows (using select count(*) as aggregate from stores
) which saves your RAM.