📄 Day 2: Pagination in Laravel

Week 19 - Advanced Laravel Features

🎯 What is Pagination and Why is it Needed?

Pagination is the process of dividing a large dataset into smaller, manageable chunks or pages. Instead of loading thousands of records at once, pagination allows you to display a subset of results with navigation controls to move between pages.

Why Pagination is Essential

💡 Real-World Example: Imagine an e-commerce site with 10,000 products. Loading all products at once would take several seconds and consume significant memory. With pagination showing 20 products per page, the page loads instantly and users can easily browse through categories.

📊 paginate() vs simplePaginate() Methods

Laravel provides two primary methods for pagination, each suited for different scenarios:

paginate() Method

The paginate() method provides full pagination with page numbers and total count.

Controller Example:
<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
    public function index()
    {
        // Paginate with 15 items per page
        $posts = Post::orderBy('created_at', 'desc')->paginate(15);
        
        return view('posts.index', compact('posts'));
    }
    
    public function search(Request $request)
    {
        $query = $request->input('query');
        
        // Pagination with search
        $posts = Post::where('title', 'like', "%{$query}%")
                    ->orWhere('content', 'like', "%{$query}%")
                    ->paginate(20);
        
        return view('posts.search', compact('posts', 'query'));
    }
}

simplePaginate() Method

The simplePaginate() method provides simple "Previous" and "Next" navigation without page numbers.

Simple Pagination Example:
<?php

namespace App\Http\Controllers;

use App\Models\Product;

class ProductController extends Controller
{
    public function index()
    {
        // Simple pagination with 25 items per page
        $products = Product::simplePaginate(25);
        
        return view('products.index', compact('products'));
    }
    
    public function categoryProducts($categoryId)
    {
        // Simple pagination with filtering
        $products = Product::where('category_id', $categoryId)
                          ->simplePaginate(20);
        
        return view('products.category', compact('products'));
    }
}

Comparison Table

Feature paginate() simplePaginate()
Page Numbers ✅ Yes ❌ No
Total Count Query ✅ Yes (COUNT query) ❌ No (more efficient)
Navigation First, Previous, Numbers, Next, Last Previous, Next only
Performance Good Better (no COUNT query)
Best For Small to medium datasets Large datasets, infinite scroll
Total Records Available Not available
⚠️ Performance Tip: For very large datasets (millions of records), use simplePaginate() to avoid the expensive COUNT query. The COUNT operation can become a bottleneck as your database grows.

🎨 Customizing Pagination Views

Laravel allows you to customize the appearance of pagination links to match your application's design.

Publishing Pagination Views

Command:
php artisan vendor:publish --tag=laravel-pagination

This creates pagination views in resources/views/vendor/pagination/:

Custom Pagination View

resources/views/vendor/pagination/custom.blade.php:
@if ($paginator->hasPages())
    <nav class="pagination-wrapper">
        <ul class="pagination">
            {{-- Previous Page Link --}}
            @if ($paginator->onFirstPage())
                <li class="disabled"><span>← Previous</span></li>
            @else
                <li><a href="{{ $paginator->previousPageUrl() }}">← Previous</a></li>
            @endif

            {{-- Pagination Elements --}}
            @foreach ($elements as $element)
                {{-- "Three Dots" Separator --}}
                @if (is_string($element))
                    <li class="disabled"><span>{{ $element }}</span></li>
                @endif

                {{-- Array Of Links --}}
                @if (is_array($element))
                    @foreach ($element as $page => $url)
                        @if ($page == $paginator->currentPage())
                            <li class="active"><span>{{ $page }}</span></li>
                        @else
                            <li><a href="{{ $url }}">{{ $page }}</a></li>
                        @endif
                    @endforeach
                @endif
            @endforeach

            {{-- Next Page Link --}}
            @if ($paginator->hasMorePages())
                <li><a href="{{ $paginator->nextPageUrl() }}">Next →</a></li>
            @else
                <li class="disabled"><span>Next →</span></li>
            @endif
        </ul>
    </nav>
@endif

Using Custom View in Blade

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

Setting Default Pagination View

AppServiceProvider.php:
<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Pagination\Paginator;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        // Use Bootstrap 5
        Paginator::useBootstrapFive();
        
        // Or use Bootstrap 4
        // Paginator::useBootstrapFour();
        
        // Or use Tailwind
        // Paginator::useTailwind();
        
        // Or use custom view
        // Paginator::defaultView('vendor.pagination.custom');
    }
}

🖼️ Pagination in Blade Templates

Basic Pagination Display

resources/views/posts/index.blade.php:
@extends('layouts.app')

@section('content')
    <div class="container">
        <h1>Blog Posts</h1>
        
        <div class="posts-grid">
            @forelse($posts as $post)
                <article class="post-card">
                    <h2>{{ $post->title }}</h2>
                    <p class="meta">
                        By {{ $post->author->name }} | 
                        {{ $post->created_at->format('M d, Y') }}
                    </p>
                    <p>{{ Str::limit($post->content, 150) }}</p>
                    <a href="{{ route('posts.show', $post) }}" class="btn">Read More</a>
                </article>
            @empty
                <p class="no-results">No posts found.</p>
            @endforelse
        </div>
        
        {{-- Pagination Links --}}
        <div class="pagination-wrapper">
            {{ $posts->links() }}
        </div>
        
        {{-- Pagination Information --}}
        <div class="pagination-info">
            Showing {{ $posts->firstItem() }} to {{ $posts->lastItem() }} 
            of {{ $posts->total() }} results
        </div>
    </div>
@endsection

Pagination with Custom Styling

Advanced Blade Template:
@extends('layouts.app')

@section('content')
    <div class="products-container">
        <div class="header">
            <h1>Products ({{ $products->total() }})</h1>
            <div class="per-page-selector">
                <span>Items per page:</span>
                <select onchange="window.location.href=this.value">
                    <option value="?per_page=10" {{ request('per_page') == 10 ? 'selected' : '' }}>10</option>
                    <option value="?per_page=25" {{ request('per_page') == 25 ? 'selected' : '' }}>25</option>
                    <option value="?per_page=50" {{ request('per_page') == 50 ? 'selected' : '' }}>50</option>
                    <option value="?per_page=100" {{ request('per_page') == 100 ? 'selected' : '' }}>100</option>
                </select>
            </div>
        </div>
        
        @if($products->hasPages())
            <div class="top-pagination">
                {{ $products->onEachSide(2)->links() }}
            </div>
        @endif
        
        <div class="products-grid">
            @foreach($products as $product)
                <div class="product-card">
                    <img src="{{ $product->image }}" alt="{{ $product->name }}">
                    <h3>{{ $product->name }}</h3>
                    <p class="price">${{ number_format($product->price, 2) }}</p>
                    <a href="{{ route('products.show', $product) }}">View Details</a>
                </div>
            @endforeach
        </div>
        
        @if($products->hasPages())
            <div class="bottom-pagination">
                {{ $products->links() }}
            </div>
            
            <div class="pagination-summary">
                <p>
                    Page {{ $products->currentPage() }} of {{ $products->lastPage() }}
                    ({{ $products->total() }} total items)
                </p>
            </div>
        @endif
    </div>
@endsection

Pagination Helper Methods

Method Description Example
links() Render pagination links {{ $items->links() }}
total() Total number of items {{ $items->total() }}
currentPage() Current page number {{ $items->currentPage() }}
lastPage() Last page number {{ $items->lastPage() }}
hasPages() Check if multiple pages exist @if($items->hasPages())
firstItem() First item number on page {{ $items->firstItem() }}
lastItem() Last item number on page {{ $items->lastItem() }}
perPage() Items per page {{ $items->perPage() }}
onFirstPage() Check if on first page @if($items->onFirstPage())
hasMorePages() Check if more pages available @if($items->hasMorePages())

🔗 Pagination with Query Strings

When working with filters and search, you need to preserve query parameters across pagination links.

Controller with Query Parameters

<?php

namespace App\Http\Controllers;

use App\Models\Product;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    public function index(Request $request)
    {
        $query = Product::query();
        
        // Apply filters
        if ($request->filled('category')) {
            $query->where('category_id', $request->category);
        }
        
        if ($request->filled('min_price')) {
            $query->where('price', '>=', $request->min_price);
        }
        
        if ($request->filled('max_price')) {
            $query->where('price', '<=', $request->max_price);
        }
        
        if ($request->filled('search')) {
            $query->where('name', 'like', '%' . $request->search . '%');
        }
        
        // Sort
        $sortBy = $request->get('sort', 'created_at');
        $sortOrder = $request->get('order', 'desc');
        $query->orderBy($sortBy, $sortOrder);
        
        // Paginate with custom per page
        $perPage = $request->get('per_page', 20);
        $products = $query->paginate($perPage);
        
        return view('products.index', compact('products'));
    }
}

Appending Query Parameters in Blade

{{-- Method 1: Append all current query parameters --}}
{{ $products->appends(request()->query())->links() }}

{{-- Method 2: Append specific parameters --}}
{{ $products->appends([
    'category' => request('category'),
    'search' => request('search'),
    'sort' => request('sort')
])->links() }}

{{-- Method 3: Append and preserve specific params --}}
{{ $products->appends([
    'category' => $category,
    'min_price' => $minPrice,
    'max_price' => $maxPrice
])->withQueryString()->links() }}

Complete Filter Example

View with Filters and Pagination:
@extends('layouts.app')

@section('content')
    <div class="container">
        <h1>Product Catalog</h1>
        
        <form method="GET" action="{{ route('products.index') }}" class="filters">
            <div class="filter-group">
                <label>Search:</label>
                <input type="text" name="search" value="{{ request('search') }}">
            </div>
            
            <div class="filter-group">
                <label>Category:</label>
                <select name="category">
                    <option value="">All Categories</option>
                    @foreach($categories as $category)
                        <option value="{{ $category->id }}" 
                            {{ request('category') == $category->id ? 'selected' : '' }}>
                            {{ $category->name }}
                        </option>
                    @endforeach
                </select>
            </div>
            
            <div class="filter-group">
                <label>Price Range:</label>
                <input type="number" name="min_price" placeholder="Min" value="{{ request('min_price') }}">
                <input type="number" name="max_price" placeholder="Max" value="{{ request('max_price') }}">
            </div>
            
            <div class="filter-group">
                <label>Sort By:</label>
                <select name="sort">
                    <option value="created_at" {{ request('sort') == 'created_at' ? 'selected' : '' }}>Newest</option>
                    <option value="name" {{ request('sort') == 'name' ? 'selected' : '' }}>Name</option>
                    <option value="price" {{ request('sort') == 'price' ? 'selected' : '' }}>Price</option>
                </select>
                <select name="order">
                    <option value="asc" {{ request('order') == 'asc' ? 'selected' : '' }}>Ascending</option>
                    <option value="desc" {{ request('order') == 'desc' ? 'selected' : '' }}>Descending</option>
                </select>
            </div>
            
            <button type="submit">Apply Filters</button>
            <a href="{{ route('products.index') }}">Clear Filters</a>
        </form>
        
        <div class="results-info">
            Found {{ $products->total() }} products
        </div>
        
        <div class="products-grid">
            @foreach($products as $product)
                <div class="product-card">
                    <h3>{{ $product->name }}</h3>
                    <p>${{ $product->price }}</p>
                </div>
            @endforeach
        </div>
        
        {{-- Preserve all filters in pagination --}}
        {{ $products->appends(request()->query())->links() }}
    </div>
@endsection

🔧 Custom Pagination Links

Manual Pagination URLs

<div class="custom-pagination">
    {{-- First Page --}}
    @if(!$products->onFirstPage())
        <a href="{{ $products->url(1) }}">First</a>
    @endif
    
    {{-- Previous Page --}}
    @if($products->previousPageUrl())
        <a href="{{ $products->previousPageUrl() }}">← Previous</a>
    @endif
    
    {{-- Page Numbers --}}
    @for($i = 1; $i <= $products->lastPage(); $i++)
        @if($i == $products->currentPage())
            <span class="active">{{ $i }}</span>
        @else
            <a href="{{ $products->url($i) }}">{{ $i }}</a>
        @endif
    @endfor
    
    {{-- Next Page --}}
    @if($products->nextPageUrl())
        <a href="{{ $products->nextPageUrl() }}">Next →</a>
    @endif
    
    {{-- Last Page --}}
    @if($products->hasMorePages())
        <a href="{{ $products->url($products->lastPage()) }}">Last</a>
    @endif
</div>

AJAX Pagination

JavaScript Implementation:
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Handle pagination clicks
    document.addEventListener('click', function(e) {
        if (e.target.matches('.pagination a')) {
            e.preventDefault();
            
            const url = e.target.getAttribute('href');
            loadProducts(url);
        }
    });
    
    function loadProducts(url) {
        fetch(url, {
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => response.text())
        .then(html => {
            // Update products container
            const parser = new DOMParser();
            const doc = parser.parseFromString(html, 'text/html');
            
            const newProducts = doc.querySelector('.products-grid').innerHTML;
            const newPagination = doc.querySelector('.pagination').innerHTML;
            
            document.querySelector('.products-grid').innerHTML = newProducts;
            document.querySelector('.pagination').innerHTML = newPagination;
            
            // Scroll to top
            window.scrollTo({ top: 0, behavior: 'smooth' });
        })
        .catch(error => console.error('Error:', error));
    }
});
</script>

Infinite Scroll Implementation

<script>
let currentPage = 1;
let lastPage = {{ $products->lastPage() }};
let loading = false;

window.addEventListener('scroll', function() {
    if (loading || currentPage >= lastPage) return;
    
    const scrollPosition = window.innerHeight + window.scrollY;
    const threshold = document.body.offsetHeight - 500;
    
    if (scrollPosition >= threshold) {
        loadMoreProducts();
    }
});

function loadMoreProducts() {
    loading = true;
    currentPage++;
    
    const url = new URL(window.location.href);
    url.searchParams.set('page', currentPage);
    
    fetch(url, {
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        }
    })
    .then(response => response.json())
    .then(data => {
        const container = document.querySelector('.products-grid');
        
        data.products.forEach(product => {
            const productHtml = `
                <div class="product-card">
                    <h3>${product.name}</h3>
                    <p>$${product.price}</p>
                </div>
            `;
            container.insertAdjacentHTML('beforeend', productHtml);
        });
        
        loading = false;
    })
    .catch(error => {
        console.error('Error:', error);
        loading = false;
    });
}
</script>

⚡ Optimizing Large Datasets

Cursor-Based Pagination

For very large datasets, cursor-based pagination is more efficient than offset-based pagination.

<?php

namespace App\Http\Controllers;

use App\Models\Log;

class LogController extends Controller
{
    public function index()
    {
        // Cursor pagination for large datasets
        $logs = Log::orderBy('created_at', 'desc')
                  ->cursorPaginate(50);
        
        return view('logs.index', compact('logs'));
    }
}

Optimization Techniques

Optimized Query Example:
<?php

namespace App\Http\Controllers;

use App\Models\Order;
use Illuminate\Http\Request;

class OrderController extends Controller
{
    public function index(Request $request)
    {
        $orders = Order::query()
            // Select only needed columns
            ->select('id', 'order_number', 'total', 'status', 'created_at')
            
            // Use eager loading to prevent N+1 queries
            ->with(['customer:id,name,email', 'items:order_id,product_name,quantity'])
            
            // Add indexes on filtered columns
            ->when($request->status, function($query, $status) {
                $query->where('status', $status);
            })
            
            // Use latest() instead of orderBy for better performance
            ->latest()
            
            // Paginate results
            ->paginate(30);
        
        return view('orders.index', compact('orders'));
    }
    
    public function exportableListing()
    {
        // For exports, use chunk instead of pagination
        Order::select('id', 'order_number', 'total', 'status')
            ->chunk(1000, function($orders) {
                foreach ($orders as $order) {
                    // Process each order
                }
            });
    }
}
💡 Performance Tips:
  • Add database indexes on columns used in WHERE and ORDER BY clauses
  • Use select() to retrieve only needed columns
  • Implement eager loading with with() to avoid N+1 queries
  • Consider using simplePaginate() for large datasets
  • Cache pagination counts for frequently accessed pages
  • Use cursor pagination for real-time feeds and logs

Caching Pagination Results

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Support\Facades\Cache;

class PostController extends Controller
{
    public function index()
    {
        $page = request('page', 1);
        $cacheKey = "posts.page.{$page}";
        
        $posts = Cache::remember($cacheKey, 3600, function() {
            return Post::with('author', 'category')
                      ->published()
                      ->latest()
                      ->paginate(20);
        });
        
        return view('posts.index', compact('posts'));
    }
}

🔄 Pagination with Eloquent Relationships

Paginating Related Models

<?php

namespace App\Http\Controllers;

use App\Models\Category;

class CategoryController extends Controller
{
    public function show(Category $category)
    {
        // Paginate products within a category
        $products = $category->products()
                            ->where('status', 'active')
                            ->orderBy('name')
                            ->paginate(24);
        
        return view('categories.show', compact('category', 'products'));
    }
    
    public function userPosts($userId)
    {
        $user = User::findOrFail($userId);
        
        // Paginate user's posts
        $posts = $user->posts()
                     ->with('category')
                     ->latest()
                     ->paginate(15);
        
        return view('users.posts', compact('user', 'posts'));
    }
}

Paginating Nested Relationships

<?php

namespace App\Http\Controllers;

use App\Models\User;

class UserController extends Controller
{
    public function show(User $user)
    {
        // Load user with paginated posts
        $user->load(['posts' => function($query) {
            $query->latest()->take(10);
        }]);
        
        // Or paginate separately
        $posts = $user->posts()->paginate(10);
        $comments = $user->comments()->paginate(20);
        
        return view('users.show', compact('user', 'posts', 'comments'));
    }
    
    public function dashboard()
    {
        $user = auth()->user();
        
        // Multiple paginated relationships
        $orders = $user->orders()->latest()->paginate(10, ['*'], 'orders_page');
        $reviews = $user->reviews()->latest()->paginate(10, ['*'], 'reviews_page');
        $favorites = $user->favorites()->paginate(10, ['*'], 'favorites_page');
        
        return view('dashboard', compact('user', 'orders', 'reviews', 'favorites'));
    }
}

View with Multiple Paginators

Blade Template:
@extends('layouts.app')

@section('content')
    <div class="user-dashboard">
        <h1>My Dashboard</h1>
        
        <section class="orders-section">
            <h2>Recent Orders</h2>
            @foreach($orders as $order)
                <div class="order-item">
                    <span>Order #{{ $order->order_number }}</span>
                    <span>${{ $order->total }}</span>
                </div>
            @endforeach
            {{ $orders->links() }}
        </section>
        
        <section class="reviews-section">
            <h2>My Reviews</h2>
            @foreach($reviews as $review)
                <div class="review-item">
                    <h3>{{ $review->product->name }}</h3>
                    <p>{{ $review->comment }}</p>
                </div>
            @endforeach
            {{ $reviews->links() }}
        </section>
        
        <section class="favorites-section">
            <h2>My Favorites</h2>
            @foreach($favorites as $favorite)
                <div class="favorite-item">
                    <h3>{{ $favorite->product->name }}</h3>
                </div>
            @endforeach
            {{ $favorites->links() }}
        </section>
    </div>
@endsection

📝 Exercises

Exercise 1: Basic Pagination

Task: Create a blog system with paginated posts.

  1. Create a PostController with an index method
  2. Paginate posts showing 12 per page
  3. Display posts with title, excerpt, and author
  4. Show pagination links at the bottom
  5. Display "Showing X to Y of Z results" information

Exercise 2: Advanced Filtering with Pagination

Task: Build a product catalog with filters.

  1. Create filters for category, price range, and search
  2. Implement sorting (price, name, date)
  3. Add a per-page selector (10, 25, 50, 100)
  4. Preserve all filters in pagination links
  5. Show active filters with option to clear them
  6. Display total results count

Exercise 3: Custom Pagination View

Task: Create a custom pagination design.

  1. Publish Laravel's pagination views
  2. Create a custom pagination template
  3. Style it with custom CSS matching your brand
  4. Add "Jump to page" functionality
  5. Include page size information

Exercise 4: AJAX Pagination

Task: Implement pagination without page reloads.

  1. Create an endpoint that returns paginated JSON data
  2. Implement JavaScript to handle pagination clicks
  3. Update content dynamically without page reload
  4. Update browser URL using History API
  5. Add loading indicator during data fetch

Exercise 5: Infinite Scroll

Task: Build infinite scroll for a social media feed.

  1. Create a posts feed with initial 20 posts
  2. Detect when user scrolls near bottom
  3. Automatically load next page of posts
  4. Append new posts to existing feed
  5. Show loading spinner while fetching
  6. Handle end of results gracefully

Exercise 6: Multiple Paginators

Task: Create a user profile with multiple paginated sections.

  1. Display user's posts (paginated separately)
  2. Display user's comments (paginated separately)
  3. Display user's photos (paginated separately)
  4. Each section should have independent pagination
  5. Use different page parameters for each section

Exercise 7: Performance Optimization

Task: Optimize pagination for large datasets.

  1. Create a table with 100,000+ records
  2. Implement cursor-based pagination
  3. Compare performance with regular pagination
  4. Add database indexes on relevant columns
  5. Implement query result caching
  6. Measure and document performance improvements

🎯 Deliverable

Project: E-Commerce Product Catalog with Advanced Pagination

Objective: Build a complete product catalog system with advanced pagination features.

Requirements:

  1. Database Setup:
    • Create products table with name, description, price, category_id, stock, status
    • Create categories table with name and description
    • Seed database with at least 100 products across 5 categories
    • Add appropriate indexes for optimization
  2. Product Listing Page:
    • Display products in a responsive grid layout
    • Show 24 products per page by default
    • Implement pagination with Bootstrap or Tailwind styling
    • Display pagination at top and bottom of results
  3. Filtering System:
    • Search by product name
    • Filter by category (dropdown)
    • Filter by price range (min and max inputs)
    • Filter by stock availability
    • Show active filters with clear buttons
    • Preserve all filters across pagination
  4. Sorting Options:
    • Sort by price (low to high, high to low)
    • Sort by name (A-Z, Z-A)
    • Sort by newest first
    • Maintain sort order in pagination links
  5. Pagination Controls:
    • Per-page selector (12, 24, 48, 96 items)
    • First, Previous, Page Numbers, Next, Last buttons
    • Show current page and total pages
    • Display "Showing X-Y of Z results"
    • Disable appropriate buttons on first/last page
  6. Category Page:
    • Create route for /category/{slug}
    • Show category name and description
    • Display paginated products in that category
    • Include breadcrumbs navigation
  7. AJAX Enhancement (Bonus):
    • Implement AJAX pagination to avoid page reloads
    • Update URL using History API
    • Add smooth scroll to top on page change
    • Show loading indicator during fetch
  8. Performance Optimization:
    • Eager load category relationships
    • Select only needed columns in queries
    • Add database indexes on filtered columns
    • Implement query result caching for popular pages

File Structure:

  • app/Models/Product.php - Product model with relationships
  • app/Models/Category.php - Category model
  • app/Http/Controllers/ProductController.php - Main controller
  • app/Http/Controllers/CategoryController.php - Category controller
  • database/migrations/xxxx_create_products_table.php - Products migration
  • database/migrations/xxxx_create_categories_table.php - Categories migration
  • database/seeders/ProductSeeder.php - Product seeder
  • resources/views/products/index.blade.php - Product listing
  • resources/views/categories/show.blade.php - Category page
  • resources/views/components/product-card.blade.php - Product component
  • routes/web.php - Route definitions

Testing Checklist:

  • ✅ Navigate between pages using pagination links
  • ✅ Apply multiple filters and verify results
  • ✅ Change sorting and verify order
  • ✅ Change items per page and verify display
  • ✅ Verify filters persist across page changes
  • ✅ Test with empty results
  • ✅ Test with only one page of results
  • ✅ Verify direct URL access with query parameters works
  • ✅ Test category pages show correct products
  • ✅ Verify performance with large datasets

Submission Requirements:

  • Complete Laravel application with all migrations
  • Seeded database with sample data
  • Screenshots showing different pagination states
  • README with setup instructions
  • Brief report on pagination performance optimization