Laravel 5-雄辩-分页结果 [英] Laravel 5 - Eloquent - Paginate results

查看:76
本文介绍了Laravel 5-雄辩-分页结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在项目中使用Laravel 5,并且具有此功能可对结果进行分页:

I'm using Laravel 5 for my project and I have this function to paginate the results:

return $query->approvate()->with( 'voti' )->get()->sortBy( function ( $sort )
{
    return $sort->voti->count();
}, 0, true );

我尝试使用paginate(),但是我需要在分页之前对集合的结果进行排序.

I have tried to use paginate() but I need the results of the collection to be ordered before the pagination.

在Laravel 4中,这种方法已在Laravel 5中删除:

In Laravel 4 there was this method that has been removed in Laravel 5:

$paginator = Paginator::make($items, $totalItems, $perPage);

订购后如何在L5中对结果进行分页?

How can I paginate the results in L5 after the ordering?

推荐答案

Laravel无法对集合进行分页,但是我写了一个助手,所以您仍然可以这样做.

Laravel has no way of paginating a collection, but I wrote a helper so you can still do this.

尝试此代码:

<?php
namespace Helpers;
use Illuminate\Support\Facades\Input;

class Paginator extends \Illuminate\Database\Eloquent\Collection {

private $pageNr;
private $perPage;
private $all;

public function paginate($perPage)
{
    $this->perPage = (int) $perPage;
    $this->pageNr = (int) $this->getCurrentPage();

    $this->all = $this->all();
    $this->items = array_slice($this->all(), $this->getCurrentPage()*$perPage-$perPage, $this->perPage);
    return $this;
}

public function getCurrentPage()
{
    $input = Input::get('page');
    if($input==null)
        return 1;
    return $input;
}

public function getLastPage()
{
    return(intval(ceil(count($this->all)/$this->perPage)));
}

public function getUrl($page)
{
    return url('zoeken?page='.$page);
}

}

您可能需要更改getUrl函数.

You might need to change the getUrl function.

用法:

$paginator = new \Helpers\Paginator(Collection $col);
$paginator->paginate(int $x);

这篇关于Laravel 5-雄辩-分页结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆