Laravel 5.2 中对有限记录使用分页

Oop*_*ops 3 pagination take laravel-5

我正在尝试对 12 条记录使用分页方法。我需要 12 个结果,其中前 6 个结果位于第一页,其余 6 个结果位于第二页。我在控制器中使用了以下代码,

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

        }
        )->where('status','1')->OrderBy('last_login','desc');
Run Code Online (Sandbox Code Playgroud)

我使用 take() 获取 12 条记录,并使用 paginate(6) 在一页中显示 6 个结果,如下所示,

$collection = $collection->paginate(6);
return View('preferred_matches')->with(array('collection'=>$collection));
Run Code Online (Sandbox Code Playgroud)

在我看来,我给出了这样的链接,

{{ $collection->links() }}
Run Code Online (Sandbox Code Playgroud)

但 take(12) 不起作用。每页显示 6 个结果,但显示的结果超过 12 个。如何使用有限的记录进行分页。提前致谢。

sab*_*buz 5

Laravel 不支持对其默认分页进行限制,但如果可以通过以下步骤对分页进行限制:

首先在模型中创建一个静态方法(假设用户模型)

第一步:在 User 模型的命名空间后面添加这两行

use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
Run Code Online (Sandbox Code Playgroud)

第二步: 在用户模型中只需键入以下方法

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;
}
Run Code Online (Sandbox Code Playgroud)

第三步:在路由或控制器中键入代码以查看结果(假设在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);
});
Run Code Online (Sandbox Code Playgroud)

希望它会起作用。