Customizing Pagination links and sliding window
Mahmoud Ramadan

Mahmoud Ramadan @mmramadan496

About: Computer Science Geek 🧐 || Software Engineer 👨‍💻 || Digging Code Creator 🚀

Location:
Mansoura, Dakahlia, Egypt
Joined:
Jan 15, 2024

Customizing Pagination links and sliding window

Publish Date: Jun 12 '25
0 0

Let’s explore some powerful Laravel pagination methods that supercharge your pagination functionality. First up is the withPath method in Laravel pagination, which customizes the URI used for pagination links:

use App\Models\User;

Route::get('/users', function () {
    // Original pagination link (without custom path)
    // E.g., http://your_app.test/users?page=1
    $users = User::paginate(15);

    // New pagination link (with custom path)
    // E.g., http://your_app.test/admin/users?page=1
    $users->withPath('/admin/users');
});
Enter fullscreen mode Exit fullscreen mode

The appends method allows you to add additional query parameters to the existing pagination URL:

use App\Models\User;

Route::get('/users', function () {
    // Original pagination link
    // E.g., http://your_app.test/users?page=2
    $users = User::paginate(15);

    // New pagination link (with the appended query string)
    // E.g., http://your_app.test/users?page=2&sort=asc
    $users->appends(['sort' => 'asc']);
});
Enter fullscreen mode Exit fullscreen mode

In some cases, you may have multiple paginations on a single page. If you use numerous paginator instances without differentiation, they may conflict with each other. To resolve this, assign a unique name to each paginator instance:

// This will generate a URL like: https://example.com/users?foo=3
User::where('votes', '>', 100)
    ->paginate(perPage: 15, columns: ['*'], pageName: 'foo');
Enter fullscreen mode Exit fullscreen mode

The onEachSide method allows you to customize the number of pagination links that are displayed before and after the current page link:

{{ $users->onEachSide(5)->links() }}
Enter fullscreen mode Exit fullscreen mode

For a deeper dive into pagination, check out this tip.

Comments 0 total

    Add comment