Home > Software engineering >  How can I implement a pager for the articles in this Laravel 8 blogging application?
How can I implement a pager for the articles in this Laravel 8 blogging application?

Time:07-31

I am working on a blogging application in Laravel 8.

Un the ArticlesController controller I have:

class ArticlesController extends FrontendController {

   public function index() {
        // All articles
        $articles = Article::paginate(12);
        return view('themes/' . $this->theme_directory . '/templates/index', 
            [
                'theme_directory' => $this->theme_directory,
                'articles' => $articles
            ]
        );
    }
}

The goal

The goal is for the posts to have a pager, with links only to the next and previous articles, not a pagination.

<!-- Pager -->
@if($articles->hasPages())
    <div >
        <ul >
            <li >
                <a  href="#">Older Posts &rarr;</a>
            </li>
            <li >
                <a  href="#">&larr; Newer Posts</a>
            </li>
        </ul>
    </div>
@endif

The problem

The default pagination code, of course, does not work for this:

@if($articles->hasPages())
    {!! $articles->withQueryString()->links() !!}
@endif
What is a viable solution for making this pager work?

CodePudding user response:

If you want Simple pagination

https://laravel.com/docs/9.x/pagination#simple-pagination

A simple view with Previous and Next buttons only is shipped with Laravel. You need to first run php artisan vendor:publish and then select Laravel Pagination.

A vendor/pagination folder will be created in the views folder, containing different layouts

You can then tell Laravel to your choice of layout by registering it in a Service Provider.

Full instructions at https://laravel.com/docs/9.x/pagination#customizing-the-pagination-view

CodePudding user response:

Here is how I solved the problem, using the section of the documentation indicated by @Snapey:

@if($articles->hasPages())
    <div >
        <ul >
            <li >
                <a  href="{{ $articles->previousPageUrl() }}">&larr; Newer Posts</a>
            </li>
            <li >
                <a  href="{{ $articles->nextPageUrl() }}">Older Posts &rarr;</a>
            </li>
        </ul>
    </div>
@endif
  • Related