Master Laravel Pagination with Bootstrap: A Step-by-Step Tutorial

Master Laravel Pagination with Bootstrap: A Step-by-Step Tutorial



Laravel 3 months ago

Laravel Pagination Using Bootstrap

Introduction

Laravel provides a robust and easy-to-use pagination system. When combined with Bootstrap, you can create clean and responsive paginated lists. This tutorial will guide you through the process of implementing pagination in your Laravel application using Bootstrap.

Prerequisites

  • Basic understanding of Laravel and Eloquent
  • Bootstrap included in your project
  • A basic Laravel application set up

Step-by-Step Guide

1. Setting Up Pagination

Laravel's pagination is straightforward. You can paginate query builder results or Eloquent collections.

PHP

// Eloquent
$posts = Post::paginate(15);

// Query Builder
$users = DB::table('users')->paginate(10);

The paginate method takes the number of items per page as an argument.

2. Using Bootstrap Pagination

To use Bootstrap's pagination styles, you need to tell Laravel to use the Bootstrap view.

PHP

use Illuminate\Pagination\Paginator;

Paginator::useBootstrap();

Typically, you'd place this in your AppServiceProvider's boot method.

3. Rendering the Pagination Links

In your Blade template, you can render the pagination links using the links method on the paginated collection:

HTML

{{ $posts->links() }}

This will generate the HTML for the pagination links using Bootstrap's CSS classes.

Complete Example

PHP

// Controller
public function index()
{
    $posts = Post::paginate(10);
    return view('posts.index', compact('posts'));
}

HTML

<h1>Posts</h1>
<ul>
    @foreach ($posts as $post)
        <li>{{ $post->title }}</li>
    @endforeach
</ul>
{{ $posts->links() }}

Customizing Pagination Links

You can customize the pagination links by passing additional options to the links method.

HTML

{{ $posts->links(['class' => 'pagination-sm']) }}

This will render the pagination links with the pagination-sm class from Bootstrap.

Additional Tips

  • Customizing Pagination View: If you need more control over the pagination links, you can create a custom view.
  • Appending Query Parameters: You can append additional query parameters to the pagination links using the appends method on the paginated collection.
  • Pagination Length: You can customize the number of page links shown using the lengthAwarePaginator method.

Example with Custom Pagination View

HTML

<ul class="pagination">
    </ul>

HTML

{{ $posts->links('vendor.pagination.custom') }}

By following these steps, you can effectively implement pagination in your Laravel application using Bootstrap, creating a user-friendly and visually appealing experience.

Would you like to see an example with a complete controller and view, including data fetching from a database?