What you can do after this lesson
You will stop loading every book on one page, and tidy the catalogue query into readable pieces. The catalogue will show a few books per page, keep the visitor's search term while they page through results, and use two reusable scopes.
Pagination
Showing 3 books is easy; showing 3,000 is not. Pagination loads one page at a time. Eloquent does the arithmetic:
$p = Book::orderBy('title')->paginate(2);Tinker printed this for the three demo books:
Illuminate\Pagination\LengthAwarePaginator total=3 pages=2 perPage=2 count=2
http://localhost:8000?page=2The paginator reads ?page= from the current request, runs a count query for the total, and loads only that page's rows. It is iterable like a collection and also knows total(), lastPage(), perPage() and nextPageUrl(). If your table is huge and you do not need page numbers, simplePaginate() skips the count query and only offers previous and next links.
The number per page should not be hard-coded. Pagelane Books reads it from the shop config you created in the configuration lesson:
->paginate(config('shop.per_page'))Showing the links
In the Blade view, after the list:
{{ $books->links() }}This prints the navigation. Two practical points. First, links must keep the search term; without it, page 2 of a search would drop the filter. withQueryString() fixes that:
->paginate(config('shop.per_page'))
->withQueryString();Testing with SHOP_PER_PAGE=2 temporarily set in .env, the link in the HTML was:
<a href="http://localhost:8091/books?search=a&page=2" rel="next" ...>and page 2 showed the third book with "Showing 3 to 3 of 3 results". An out-of-range page such as ?page=9 simply showed no books. Second, the default pagination view that ships with Laravel is written with Tailwind CSS class names. This project does not load Tailwind, so the arrow icons (inline SVG) would render at full size. The layout gets one small rule:
nav[role=navigation] svg { width: 1.25rem; height: 1.25rem; }You can instead publish Laravel's pagination views with php artisan vendor:publish --tag=laravel-pagination and restyle them, or use a built-in Bootstrap view; both are described in the pagination chapter of the Laravel documentation. For total counts shown to visitors, use $books->total(); the search heading in the view now says Results for "a": 3 using it, because count() only counts the current page.
Scopes: name your conditions
The catalogue query is growing: published books only, a search across title and author, a category eager load. Repeating those where calls in several controllers invites inconsistency. A local scope gives a condition a name. In Laravel 13.42.0 you can mark a protected method with the Scope attribute:
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;
/** Books whose publication date has arrived. */
#[Scope]
protected function published(Builder $query): void
{
$query->whereNotNull('published_on')->where('published_on', '<=', now()->toDateString());
}
/** Match a search term against title or author. */
#[Scope]
protected function search(Builder $query, ?string $term): void
{
if ($term === null || $term === '') {
return;
}
$query->where(function (Builder $query) use ($term) {
$query->where('title', 'like', "%{$term}%")
->orWhere('author', 'like', "%{$term}%");
});
}The older style, a method named scopePublished without the attribute, is also valid, and you will see it in many tutorials. Using the scopes:
Book::published()->count(); // 3
Book::search('ada')->pluck('title'); // ["Salt and Signal"]
Book::published()->search('ada')->toSql();select * from "books" where "published_on" is not null and "published_on" <= ? and ("title" like ? or "author" like ?)Notice the grouped parentheses around the two like conditions. Wrapping orWhere in a closure keeps it from combining with the other conditions in unexpected ways, a common source of bugs. Now the controller reads like a sentence:
$books = Book::query()
->published()
->search($search)
->with('category')
->orderBy('title')
->paginate(config('shop.per_page'))
->withQueryString();
return view('books.index', ['books' => $books, 'search' => $search]);Eager loading the category avoids the N+1 problem from the relationships lesson. Global scopes, which apply to every query on a model, also exist, but are best left until you are comfortable, since they hide conditions.
Common mistakes
- Forgetting
withQueryString(), so filters vanish on page 2. - Using
count()instead oftotal()for the heading and getting only the page's size. - Using
orWherewithout grouping, which leaks past other conditions. - Paginating an already-fetched collection. Call
paginate()on the query, beforeget(). - Large per-page values taken from user input. If you let users choose, clamp it to a safe maximum.
Exercise
Add a scope inCategory($slug) to Book that filters by category slug, use it for a ?category=fiction filter on the catalogue, and keep it in the pagination links.
Show one possible answer
#[Scope]
protected function inCategory(Builder $query, ?string $slug): void
{
if ($slug) {
$query->whereHas('category', fn ($q) => $q->where('slug', $slug));
}
}->published()->search($search)->inCategory($request->query('category'))withQueryString() already keeps every query parameter, so category survives in the page links. Next: filling the database with test data using factories.
Key points
- paginate(n) loads one page of n rows, reads the page number from the query string, and returns a paginator that knows totals and links.
- Calling links() in Blade prints page links, and withQueryString() keeps filters such as search in those links.
- The default pagination view uses Tailwind class names, so without Tailwind you need a little CSS, a simple paginator or your own view.
- A local scope packages a reusable condition as a method on the model; Laravel 13 supports the Scope attribute as well as the older scope method prefix.
- Scopes chain like normal query methods, so published()->search($term) reads like the question you are asking.