Laravel Intermediate Blade & HTTP · 7 min read

Laravel Pagination with the Query String

Lesson 14 of 33 in the Laravel learning path.

How do I paginate lessons and keep the search query?

paginate() loads one page of lessons and knows how many pages exist. The links it renders must keep the search the user already typed, or page 2 forgets q and shows a different set. withQueryString() copies the current query string onto those links, including q, and replaces the page parameter itself.

The controller builds the page with Lesson::query()->orderBy('title')->paginate(10)->withQueryString(). This Blade file reprints the search form from the q parameter and prints the pager with the same helper, so a catalog search for algebra stays on algebra when the reader moves to the next page.

Syntax & Parameters

Syntax
Lesson::query()->orderBy('title')->paginate(10)->withQueryString()

Example

Interactive preview available
resources/views/lessons/index.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Lessons</title>
</head>
<body>
    <h1>Lessons</h1>

    <form method="get" action="{{ route('lessons.index') }}">
        <label for="lesson-search">Search</label>
        <input id="lesson-search" type="search" name="q" value="{{ request('q') }}">
        <button type="submit">Search</button>
    </form>

    <p>
        Showing {{ $lessons->firstItem() ?? 0 }} to {{ $lessons->lastItem() ?? 0 }}
        of {{ $lessons->total() }} lessons
    </p>

    @forelse ($lessons as $lesson)
        <article>
            <h2>
                <a href="{{ route('lessons.show', $lesson) }}">{{ $lesson->title }}</a>
            </h2>
            <p>{{ $lesson->track }}</p>
        </article>
    @empty
        <p>No lessons match this search.</p>
    @endforelse

    {!! $lessons->withQueryString()->links() !!}
</body>
</html>

Expected Output

GET /lessons?q=algebra&page=2

Showing 11 to 20 of 34 lessons
Algebra I
Algebra II

Pager hrefs:
/lessons?q=algebra&page=1
/lessons?q=algebra&page=3

GET /lessons?q=algebra&page=2 without withQueryString drops q, and page 2 is no longer the algebra search.

Line-by-Line Walkthrough

  1. The controller query is Lesson::query()->when the q parameter is filled, constrain title, then orderBy('title')->paginate(10)->withQueryString().
  2. paginate(10) returns a LengthAwarePaginator with 10 lessons for the requested page and a count of the full match.
  3. The form is method get, so a search puts q on the URL instead of hiding it in the POST body.
  4. The input value is request('q'), escaped by Blade braces, so the box shows the current search again.
  5. firstItem, lastItem, and total describe the page. On an empty match, firstItem and lastItem are null and the template prints 0.
  6. forelse prints each lesson, or the empty sentence when this page has no rows. Lesson titles use escaped braces.
  7. links() returns the pager HTML. The raw Blade echo is limited to that helper because the paginator escapes query values itself.
  8. withQueryString() adds the current query, including q, to every page link, and the paginator supplies its own page number.
  9. A request for /lessons?q=algebra&page=2 keeps q=algebra on Previous and Next. Calling links() without the helper would drop q and list every lesson on page 2.

Common Pitfalls & Security

Pagination links are ordinary URLs. If they lose the search parameter, the next page is a different query and the reader thinks lessons vanished. The search string is user input and belongs in escaped Blade output, while the pager HTML comes from Laravel.

  • links() without withQueryString, and without appends, drops q. Page 2 then shows the unfiltered catalog.
  • Escaping the pager with {{ $lessons->links() }} prints the tags as text. Use the raw echo only for links(), not for the lesson title or the search box.
  • A POST search cannot be replayed by a page link. Use GET when the result should be a URL someone can open again.
  • paginate() runs a count query. A million-row report that does not need page numbers can use simplePaginate instead.
  • LIKE wildcards in q are still wildcards. A search of % matches every title. Escape % and _ when the product treats them as literal characters.
  • Do not trust a page value from the query to build SQL yourself. paginate reads it and binds the limit and offset.

Best Practices & Modern Standards

Call withQueryString() on the paginator in the controller, or again in the view, before you render links(). Keep the search form on GET with a named q field, and fill the input from the request so a refresh shows the same search. Order the query by a stable column so a row does not jump between pages while someone is reading.

Escape every lesson field in Blade. Leave the pager to links(), which builds the URLs and escapes the query values. When a filter has several fields, withQueryString keeps all of them, so you do not have to append each name by hand.

Real-World Use

A student searches the catalog for algebra and opens page 2. The pager links still carry q=algebra, so the second page stays inside that search. The form shows algebra in the box, and the student can copy the URL and get the same page later.

Frequently Asked Questions

Where do I call withQueryString?

On the paginator, either in the controller after paginate or in the view as $lessons->withQueryString()->links(). Both copy the current query onto the page links.

Why is the search form a GET?

Page links are GET requests. A GET form puts q in the query string, which is the value withQueryString copies. A POST body is not part of those links.

Why does the pager use a raw Blade echo?

links() returns HTML. Escaping it would show the tags as text. The paginator escapes the query values when it builds the hrefs. Escape the lesson title and the search value yourself.

What does paginate(10) put in the URL?

Laravel reads the page query parameter and shows 10 rows for that page. withQueryString keeps other parameters, such as q, beside page.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…