2017-09-17 53 views
0

我有這個問題,當我手動創建laravel中的paginator以顯示100個產品時,在視圖中頁面顯示數據並且很好,但是如果我放了一個限制,例如我想每個頁面有10個元素,他在第一頁中顯示了十個元素,當我點擊下一個第二頁時,顯示了相同的十個元素,數據不會改變,爲什麼?Laravel分頁數據不會隨着刀片中的render()更改

控制器:

public function show() 
    { 


     $client = new Client([ 
      // Base URI is used with relative requests 
      'base_uri' => 'http://www.mocky.io/v2/59bec4d926000046015261a7', 
      // You can set any number of default request options. 
      'timeout' => 2.0, 
     ]); 

     $response = $client->request('GET', ''); 
     $code = $response->getStatusCode() 
     $products = json_decode($response->getBody()->getContents()); 

     } 

    $products = new Paginator($products, 10 , 
     Paginator::resolveCurrentPage(), 
     ['path' => Paginator::resolveCurrentPath()]); 


     return view('products/list', compact('products')); 

    } 

查看與10個元件的陣列結果的

@extends('layout.master') 

@section('content') 
<h2> Products</h2> 
<ul> 

    @if($products) 
    @foreach($products as $product) 
     <li> {{ $product->name}} - {{ $product->value}}</li> 
     @endforeach 
     @endif 

</ul> 
{{$products->render()}} 

@endsection 

實施例,3元 頁//這是與發明的信息的例子。

array {0,1,2,3,4,5,6,7,8,9} 

Page 1 

0 - 0 
1 - 1 
2 - 2 

Page 2 // the data dont change , why ? 

0 - 0 
1 - 1 
2 - 2 
+0

您正在使用哪個Paginator類?如果是自定義班級,請向我們展示代碼 – Paras

+0

@Paras我解釋我不好,我使用手動創建laravel分頁器的方法「Illuminate \ Pagination \ Paginator」,鏈接https://laravel.com/docs/ 5.4 /分頁,在當前代碼中我使用Paginator –

回答

0

沒有魔法,paginators會打電話給你的控制器功能的每一頁。該請求將包含分頁信息。你的工作是實際選擇和切片的頁面。該paginator只是簡單介紹它...這是工作的重要組成部分...

// DB::select returns an array, thus we have to build the paginator ourselves... 
    $comm = DB::select('select bla bla bla from comments where this and that... 
         order by approved ASC'); 

    // this basically gets the request's page variable... or defaults to 1 
    $page = Paginator::resolveCurrentPage('page') ?: 1; 

    // Assume 15 items per page... so start index to slice our array 
    $startIndex = ($page - 1) * 15; 

    // Length aware paginator needs a total count of items... to paginate properly 
    $total = count($comm); 

    // Eliminate the non relevant items... 
    $results = array_slice($comm, $startIndex, 15); 

    $comments = new LengthAwarePaginator($results, $total, 15, $page, [ 
     'path' => Paginator::resolveCurrentPath(), 
     'pageName' => 'page', 
    ]); 
    return view('backend/comments', compact('comments')); 
+0

當我使用paginator與雄辯有什麼不同時,在雄辯的情況下我不需要使用$頁面,當控制器發送get page = 2時他會自動更改de信息。 –

+0

Eloquent方法User :: paginate(15)將返回一個LengthAwarePaginator。你使用的是,如果我記得的話,用戶:: simplePagination()方法返回Paginate對象...如果你想處理已知的結果集長度,則需要LengthAwarePaginator ... – Serge

0

你需要像這樣添加頁面名稱(要求PARAM表示頁碼的名稱):

$products = new Paginator($products, 10, null, 
     ['path' => Paginator::resolveCurrentPath(), 
     'pageName' => 'page']); 
+0

我已經做了更改,但結果是一樣的,我還缺少了什麼? –