3

12 レコードに paginate メソッドを使用しようとしています。最初の 6 つの結果が最初のページに表示され、残りの 6 つの結果が 2 ページ目に表示される 12 の結果が必要です。コントローラーで以下のコードを使用しました。

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

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

take() を使用して 12 レコードを取得し、paginate(6) を使用して 6 つの結果を 1 ページに表示しました。

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

私の見解では、このようなリンクを提供しました。

{{ $collection->links() }}

しかし、take(12) は機能していません。各ページに 6 件の結果が表示されますが、12 件を超える結果が表示されています。ページネーションに限られたレコードを使用するにはどうすればよいですか。前もって感謝します。

4

3 に答える 3

4

Laravel はデフォルトのページネーションの制限をサポートしていませんが、次の手順でページネーションに制限を設定できる場合:

最初にモデル内に静的メソッドを作成します(ユーザーモデルを想定)

最初のステップ: User モデルの名前空間の後にこの 2 行を追加します

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

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;
}

3 番目のステップ:ルートまたはコントローラーにコードを入力して、結果を確認します ( を想定routes.php)

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);
});

うまくいけば、うまくいくでしょう。

于 2017-04-09T06:34:55.850 に答える