Laravel Eloquent pagination control page number wi

2019-06-22 09:36发布

问题:

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')

Controller:

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

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

回答1:

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.

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

The default convention is

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

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

Check out https://laravel.com/docs/5.4/pagination for more info