How to use pagination in laravel 5 with raw request

I have a simple question and I have not found what I need.

I need to calculate the distance between geocoding points t2 for a list of stores. I also need it to be paginated for WebService.

This works, but there is no result as a result:

public function stores(){
    return Store::paginate(10);
}

And the result:

{
   total: 4661, 
   per_page: 10, 
   current_page: 6, 
   last_page: 467,
   next_page_url: "WS_URL/stores/?page=7",
   prev_page_url: "WS_URL/stores/?page=5", from: 51,
   to: 60, 
   data: [ { 
        id: "51", 
        name: "Sprouts",
        .
        .
        lng: "-118.359688", 
        lat: "33.808281", 
        country: "usa" 
        },
    .
    .
    .
    ]}

But I need this code:

public function stores(){
    return DB::table('stores')
        ->selectRaw(' *, distance(lat, ?, lng, ?) as distance ')
        ->setBindings([ 41.123401,1.2409893])
        ->orderBy('distance')
        ->paginate($this->limit);
}

And this is the result:

{total: 0,
    per_page: 10,
    current_page: 1,
    last_page: 0,
    next_page_url: null,
    prev_page_url: null,
    from: 1,
    to: 10,
    data: [{
        id: "3686",
        name: "Bon Area", 
        .
        .
        lng: "1.602016",
        lat: "41.266823",
        distance: "0.15091"
        },
    .
    .
    .
    ]
}

I need next_page_urlandprev_page_url

Any ideas?

+4
source share
2 answers

Use the method selectRawfor the Eloquent model.

Store::selectRaw('*, distance(lat, ?, lng, ?) as distance', [$lat, $lon])
    ->orderBy('distance')
    ->paginate(10);

In this case, Laravel queries the database for the number of rows (using select count(*) as aggregate from stores) that saves your RAM.

+4
source

, ! , , 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;
}

setBindings ([$ lat, $lon])

:

public function stores($lat, $lon){
    return $stores = DB::table('stores')
        ->selectRaw(" *, distance(lat, {$lat}, lng, {$lon}) as distance ")
        ->orderBy('distance')
        ->paginate($this->limit);
}
0

All Articles