2017-03-06 5 views
0

12ページのレコードに対してpaginateメソッドを使用しようとしています。最初の6つの結果が最初のページに、残りの6つの結果が2番目のページに表示される12の結果が必要です。私はlaravelの限られたレコードに対してページ分割を使用する5.2

$collection = User::take(12)->whereHas('roles', function($q) { 
      $q->where('slug', 'member'); 

     } 
     )->where('status','1')->OrderBy('last_login','desc'); 

、コントローラに以下のコードを使用し、私は12を記録し、使用のpaginateを取得するためにテイクを()を使用し(6)、このように1ページに私には

$collection = $collection->paginate(6); 
return View('preferred_matches')->with(array('collection'=>$collection)); 

を6件の結果を表示します表示、私はこのようなリンクを与えた

{{ $collection->links() }} 

しかし、テイク(12)は動作していません。各ページに6件の結果が表示されますが、12件以上の結果が表示されています。限られたレコードをページ分割に使用するにはどうすればよいですか。前もって感謝します。

+0

代わりに 'take'することができますの'limit(12)'を試してください。 –

+0

しかし、それでも効果はありません。私が必要とするのは、12レコード、ページあたり6件の結果を表示することです。 – Rose

答えて

2

Laravelはデフォルトのページ付けの制限をサポートしていませんが、制限は、次の手順で改ページ上に配置することができた場合:

まず第一に

をモデル内の静的メソッドを作成します(と仮定ユーザーモデル)ステップ:

use Illuminate\Pagination\LengthAwarePaginator; 
use Illuminate\Support\Collection; 

Userモデルの名前空間の後に第二ステップ、この2行を追加します。すぐ下を入力し、ユーザーモデル内を方法

public static function customPaginate($items,$perPage) 
{ 
    //Get current page form url e.g. &page=6 
    $currentPage = LengthAwarePaginator::resolveCurrentPage(); 

    //Create a new Laravel collection from the array data 
    $collection = new Collection($items); 

    //Define how many items we want to be visible in each page 
    $perPage = $perPage; 

    //Slice the collection to get the items to display in current page 
    $currentPageSearchResults = $collection->slice($currentPage * $perPage, $perPage)->all(); 

    //Create our paginator and pass it to the view 
    $paginatedSearchResults = new LengthAwarePaginator($currentPageSearchResults, count($collection), $perPage); 

    return $paginatedSearchResults; 
} 

第三工程:経路またはコントローラタイプ結果を確認するためのコードでは

Route::get('/', function(){ 
    $users = DB::table('users')->limit(20)->get(); 
    $paginated_result = App\User::customPaginate($users,3); 
    //dd($paginated_result); 
    return view('show')->with('paginated_result',$paginated_result); 
}); 

うまくいけば、それが動作する(routes.phpに仮定します)。コレクションはperPageパラメータよりも小さい場合

+0

この方法に感謝します:) – Rose

0

前の回答についてだけ、わずか更新は、多少のバグがあり、アイテムの配列が空である、これは交換することによって修正することができます:

$currentPageSearchResults = $collection->slice($currentPage * $perPage, $perPage)->all();

静的関数で

$currentPageSearchResults = ($items->count() > $perPage) ? $collection->slice($currentPage * $perPage, $perPage)->all() : $collection->all();

によります。 @sabuzさん、ありがとう!

$currentPage = LengthAwarePaginator::resolveCurrentPage();:;)前の回答についてのもう一つだけ更新

0

は、あなたが「最後のページ」のデータにアクセスしようとした場合、それは空の結果をもたらすでしょう、あなたはこの行を変更する必要があり、この問題を解決するにはこれら二つのため

$currentPage = LengthAwarePaginator::resolveCurrentPage(); $currentPage = $currentPage - 1;

私はそれが誰かを役に立てば幸い...

関連する問題