簡體   English   中英

Laravel 5.1中的手動分頁

[英]Manual Pagination in Laravel 5.1

我有一個從數據庫中獲取的結果數組(超過25個結果)。 我正在嘗試在我的應用程序中實現Laravel分頁。

我想要的是分頁讀取結果。

我得到的是相同結果的分頁。

我到目前為止使用的代碼:

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

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

我確實得到了分頁,但是在進行檢查時,在第2頁上,在第3頁上,依此類推。等等。在分頁的所有后續頁面上,我都得到了在分頁的第1頁上可見的結果。

請幫助我。 非常感謝您的幫助。

編輯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);
?>

PS:我正在嘗試自己學習如何在Laravel 5.1中集成自定義分頁

分頁器渲染器將在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)
<?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]);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM