Laravel 5.1中的手动分页

时间:2016-06-04 12:10:25

标签: php laravel pagination laravel-5.1

我从数据库中获取了一系列结果(超过25个结果)。我正在尝试在我的应用程序中实现Laravel分页。

我想要的是对获取的结果进行分页。

我得到的是相同结果的分页。

到目前为止我使用的代码:

$result = array_slice($fetchAllProducts, 0, 12);

$paginateResults = new Illuminate\Pagination\LengthAwarePaginator($result, count($fetchAllProducts), 12);

我确实得到了分页,但是在进行检查时,在第2页,第3页等等。我得到了分页的所有后续页面上分页的第1页上显示的结果。< / p>

请帮助我解决这个问题。任何帮助都非常感谢。

编辑1:代码

<?php
$productsInParent = $category->products;
$productsInParentCategory = new Illuminate\Support\Collection;
$allProducts = $allProductsFromChild = [];

foreach($productsInParent as $prodInParent) {
    $allProducts[] = $prodInParent;
}

foreach($category->childs as $child) {
    foreach($child->products as $productsInChildren) {
        $allProductsFromChild[] = $productsInChildren;
    }
}

$fetchAllProducts = array_merge($allProducts, $allProductsFromChild);

$result = array_slice($fetchAllProducts, 0, 12);

$paginateResults = new Illuminate\Pagination\LengthAwarePaginator($result, count($fetchAllProducts), 12);
?>

P.S。:我正在努力学习如何在Laravel 5.1中集成自定义分页

2 个答案:

答案 0 :(得分:0)

paginator呈现将在URL中设置page参数,该参数应该用于确定切片的偏移量:

$result = array_slice($fetchAllProducts, Request::get('page',1)-1, 12); 

但是,我建议更改查询以在一个查询中获取所有结果,并使用QueryBuilder分页器,如:

$categories = $catgory->childs->pluck('id')->all();
$categegories[] = $category->id;

$paginateResults =Product::whereIn('category_id', $categories)->paginate(12)

答案 1 :(得分:0)

<?php

namespace App\Http\Controllers;

use Illuminate\Pagination\LengthAwarePaginator as Paginator;
// use Illuminate\Pagination\Paginator;
use Illuminate\Http\Request;
use App\Product;
class MyController extends Controller
{
    public function index(Request $request){
        $items = Product::all();

        $filter_products = []; // Manual filter or your array for pagination

        foreach($items as $item){
            if($item['id']>40 && $item['id']<50){
                array_push($filter_products, $item);
            }
        }

        $count = count($filter_products); // total product for pagination
        $page = $request->page; // current page for pagination

        // manually slice array of product to display on page
        $perPage = 5;
        $offset = ($page-1) * $perPage;
        $products = array_slice($filter_products, $offset, $perPage);

        // your pagination 
        $products = new Paginator($products, $count, $perPage, $page, ['path'  => $request->url(),'query' => $request->query(),]);
        // use {{ $products->appends($_GET)->links() }} to dispaly your pagination
        return view('index',['products' => $products]);
    }
}