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

标签 pagination laravel-5.2 take

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

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

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

我使用 take() 获取 12 条记录并使用 paginate(6) 在一页中显示 6 个结果,如下所示,
$collection = $collection->paginate(6);
return View('preferred_matches')->with(array('collection'=>$collection));

在我看来,我给出了这样的链接,
{{ $collection->links() }}

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

最佳答案

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

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

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

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

第二步:在 User 模型中只需输入以下方法
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;
}

第三步:在路由或 Controller 中键入代码以查看结果(假设在 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);
});

希望它会起作用。

关于pagination - 对 Laravel 5.2 中的有限记录使用分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42618351/

相关文章:

php - laravel 5.2 Blade 模板无法解析

c# - LINQ to SQL 分组依据与 take

f# - 漏洞 ? Seq.take 10 运行良好,Seq.take 100 不起作用

javascript - 使用tablesorter插件处理大量数据

javascript - 是否可以在没有背景网格的情况下进行分页?

php - 分页工作正常但出现错误

php - 仅通过 Auth 中间件和基于 token 的身份验证访问存储文件夹中的文件

python - 下一个,上一个,计数的 Django 分页

laravel - 如何在 php artisan 中进行测试 POST 请求?

c# - LINQ 与跳过和采取