Laravel雄辩的分页控制页码与路线 [英] Laravel Eloquent pagination control page number with route

查看:244
本文介绍了Laravel雄辩的分页控制页码与路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Articles::paginate(10) 此代码将返回前10篇文章,如果我想返回带有路由的下10篇文章怎么办?例如,URL mypage.com/articles/2将返回数据库中的第二10条文章.
到目前为止,这是我所拥有的:
路线:

Articles::paginate(10) This code will return the 1st 10 articles, what if I want to return the next 10 articles with route? For example the url mypage.com/articles/2 will return the 2nd 10 articles from database.
This is so far what I have:
Route:

Route::get('articles/{page_number}', 'Controller@getArticles')

控制器:

public function getArticles($page_num)
{
    $perPage = 10;
    Articles::getPaginator()->setCurrentPage($page_num);
    $articles = Articles::paginate($perPage);
    return $articles;
}

我可以有类似Articles::pageNumber($page_number)->paginate($perPage);的东西吗?

Can I have something like Articles::pageNumber($page_number)->paginate($perPage);?

推荐答案

Laravel分页器会自动检查查询字符串中page的值并将其用于分页结果.结果还将自动生成下一个和上一个链接,以帮助您直接添加它们.您无需进行任何更改即可使其工作.

Laravel paginator automatically checks for the the value of page in query string and uses it to paginate the results. The result also automatically generates the next and previous links to help you add them directly. You don't need to change anything to make it work.

在您的情况下,可以在视图中使用$articles->links()生成分页导航按钮.但是,如果要手动设置页面,则可以执行此操作.

In your case you can use $articles->links() in your view to generate the pagination navigation buttons. But if you want to manually set the page then you can do this.

$articles = Articles::paginate(5, ['*'], 'page', $pageNumber);

默认分页方法采用以下参数.

The default paginate method takes the following parameters.

public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null);

默认约定为

mypage.com/articles?page=2
mypage.com/articles?page=3

此外,如果您使用$articles->links()生成导航按钮,则还可以自定义CSS.

Also if you use $articles->links() to generate the navigation button, you can also customize the css.

查看 https://laravel.com/docs/5.4/pagination 了解更多信息

这篇关于Laravel雄辩的分页控制页码与路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆