How can I paginate an array of objects in Laravel?

纵然是瞬间 提交于 2019-12-06 02:43:28

Your approach to query the data is extremely inefficient. Fetch your data in one query. Nested traversing is not only hard to read but also a performance killer.

To the pagination problem:

Laravel provides a Pagignator Factory. With it you will be able to build your own Paginator with your own data.

It's as easy as

$units = Paginator::make($unit, count($unit), 10);

if you're using the Facade. Otherwise Illuminate\Pagination\Factory is the class you are looking for.

Maged Hamid

I got a better solution to paginate array result and I found the answer here

Paginator::make function we need to pass only the required values instead of all values. Because paginator::make function simply displays the data send to it. To send the correct offset paginated data to the paginator::make, the following method should be followed

    $perPage = 5;   
    $page = Input::get('page', 1);
    if ($page > count($publishedSaleUnits) or $page < 1) { $page = 1; }
    $offset = ($page * $perPage) - $perPage;
    $perPageUnits = array_slice($publishedSaleUnits,$offset,$perPage);
    $pagination = Paginator::make($perPageUnits, count($publishedSaleUnits), $perPage);
Shahrukh Anwar

You can try my code with your own array,

$page = isset($request->page) ? $request->page : 1; // Get the page=1 from the url
$perPage = $pagination_num; // Number of items per page
$offset = ($page * $perPage) - $perPage;

$entries =  new LengthAwarePaginator(
    array_slice($contact_list, $offset, $perPage, true),
    count($contact_list), // Total items
    $perPage, // Items per page
    $page, // Current page
    ['path' => $request->url(), 'query' => $request->query()] // We 
       need this so we can keep all old query parameters from the url
);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!