Laravel 12 Pagination Query Example

Using Laravel 12, you can paginate database records using Eloquent or Query Builder. Laravel provides three pagination methods:

1. `paginate()` → Standard pagination with page numbers.
2. `simplePaginate()` → Uses “Next” and “Previous” links instead of numbered pages.
3. `cursorPaginate()` → Efficient pagination for large datasets using cursors.

1. Eloquent Pagination Example

<?php
use App\Models\Post;
$posts = Post::paginate(10); // Fetch 10 posts per page
return view('posts.index', compact('posts'));
?>

Blade View (posts/index.blade.php)

```blade
@foreach($posts as $post)
<h2>{{ $post->title }}</h2>
@endforeach
<!-- Pagination Links -->
{{ $posts->links() }}

2. Simple Pagination (Next/Prev Buttons)

<?php
$posts = Post::simplePaginate(10);
?>

Use when you don’t need numbered links (better performance).

3. Cursor Pagination (For Large Datasets)

<?php
$posts = Post::cursorPaginate(10);
?>

Best for performance when paginating millions of records.

4. Pagination Using Query Builder

<?php
use Illuminate\Support\Facades\DB;
$posts = DB::table('posts')->paginate(10);
?>

5. Customizing Pagination in Laravel

<?php
$posts = Post::paginate(10, ['*'], 'custom_page');
?>

This changes the default page query parameter (`?page=1`) to `?custom_page=1`.