laravel pagination with raw query code example

Example 1: laravel paginate raw sql

$items = DB::table('team')   
    ->selectRaw('SELECT *,earth_distance(ll_to_earth(team.lat, team.lng), ll_to_earth(23.1215939329,113.3096030895)) AS distance')
    ->whereRaw('earth_box(ll_to_earth(23.1215939329,113.3096030895),1000) @> ll_to_earth(team.lat, team.lng)')
    ->paginate(10);

foreach($items as $item) {
    echo $item->distance;
}

Example 2: laravel pagination having raw query not working

$curPage = \Illuminate\Pagination\Paginator::resolveCurrentPage();
        $total = $model->get()->count();
        $items = $model->forPage($curPage, $showPerPag)->get();
        $paginated = new \Illuminate\Pagination\LengthAwarePaginator($items, $total, $showPerPage, $curPage, ['path' => request()->url(), 'query' => request()->query()]);

Example 3: laravel pagination having raw query not working

// This works as expected       

		$curPage = \Illuminate\Pagination\Paginator::resolveCurrentPage();
        $total = $model->get()->count();
        $items = $model->forPage($curPage, $showPerPag)->get();
        $paginated = new \Illuminate\Pagination\LengthAwarePaginator($items, $total, $showPerPage, $curPage, ['path' => request()->url(), 'query' => request()->query()]);

Tags:

Php Example