Skip to content

Instantly share code, notes, and snippets.

@yvonnel098
Created October 4, 2020 19:17
Show Gist options
  • Save yvonnel098/679561900ab50d643c3b7c16792b0825 to your computer and use it in GitHub Desktop.
Save yvonnel098/679561900ab50d643c3b7c16792b0825 to your computer and use it in GitHub Desktop.
Laravel Simple Pagination
use DB;
use Illymincate\Database\Eloquent\Model;
use Illuminate\Pagination\paginator;
//set $pageSize to items per page
//set $conditions to where $conditions
//set $page to current page number
$results = DB::table('tableName')
->where($conditions)
->offset(($page-1)*$pageSize)
->limit($pageSize)
->orderByDesc("id")
->get();
$items = new Paginator(
$results->values(),
$pageSize,
$page, [
'path' => \Request:;url(),
'query' =>[
'page'=>$page
]
]);
@yvonnel098
Copy link
Author

Laravel recommends simple pagination for large datasets. Here's one way of doing it. I realize that using an Offset in SQL query is not optimum. I'm doing it this way because my data is dynamic. As user read one page, the status of the back end data with lesser "id" may become available. If I use an "id" based search instead of offset, the user will miss the new data. If you are dealing with static data that won't change while you are running the query, instead of using "offset", use a compare on "id" (between max and min on a page). This will avoid page drift and improve performance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment