What you can do after this lesson
You will connect the shop's tables: a book belongs to a category, can have many tags, and receives reviews from users. You will read across those links in one line, and you will know the performance trap hiding in loops.
Three kinds of relationship
Data in a shop is connected, and relational databases express links with foreign keys. Eloquent turns those links into methods:
| Relationship | Example | Method |
|---|---|---|
| One to many | A category has many books | hasMany (parent), belongsTo (child) |
| Many to many | A book has many tags, a tag many books | belongsToMany on both |
| One to one | A user has one profile | hasOne, belongsTo |
The rule for the first kind: the model whose table holds the foreign key belongs to the other. books.category_id lives on books, so Book belongsTo Category, and Category hasMany Book.
The new tables
Three more migrations, generated with make:model Tag -m, make:model Review -m and make:migration create_book_tag_table. The interesting parts:
// tags
$table->string('name')->unique();
$table->string('slug')->unique();
// reviews
$table->foreignId('book_id')->constrained()->cascadeOnDelete();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->unsignedTinyInteger('rating');
$table->text('body')->nullable();
$table->unique(['book_id', 'user_id']); // one review per user per book
// book_tag (the pivot table)
$table->foreignId('book_id')->constrained()->cascadeOnDelete();
$table->foreignId('tag_id')->constrained()->cascadeOnDelete();
$table->primary(['book_id', 'tag_id']);A pivot table has one row per link. Its default name joins both singular table names alphabetically, so book_tag, which is why Eloquent finds it without configuration. After php artisan migrate the three tables exist.
The relationship methods
In Book:
public function category(): BelongsTo
{
return $this->belongsTo(Category::class);
}
public function tags(): BelongsToMany
{
return $this->belongsToMany(Tag::class);
}
public function reviews(): HasMany
{
return $this->hasMany(Review::class);
}The other side: Category::books() is hasMany(Book::class), Tag::books() is belongsToMany(Book::class), Review has book() and user() as belongsTo, and User::reviews() is hasMany(Review::class). Add the import for each return type, for example Illuminate\Database\Eloquent\Relations\HasMany.
Using them
Access the relation as a property to get the related models, or call it as a method to get a query you can keep building. This tinker session ran against the demo data (a throwaway user and two tags were created first):
$book = Book::find(1);
echo $book->category->name; // Fiction
echo Category::where('slug', 'fiction')->first()->books->pluck('title')->implode(', ');
$book->tags()->attach([$cozy->id, $sea->id]);
echo $book->tags->pluck('name')->implode(', '); // Cosy, Sea
echo $sea->books->pluck('title')->implode(' | '); // from the other side
$book->tags()->detach($cozy->id); // 1 tag left
$book->tags()->sync([$cozy->id, $sea->id]); // 2 tags again
$book->reviews()->create(['user_id' => $user->id, 'rating' => 5, 'body' => 'A calm, lovely read.']);
echo $book->reviews()->count(), $book->reviews()->avg('rating'); // 1 and 5Fiction
The Quiet Harbour, Paper Lanterns
Cosy, Sea
The Quiet Harbour | Salt and Signal
1 tag left
2 tags after sync
reviews: 1, avg: 5$book->tags (property) returns a collection; $book->tags() (method) returns the relation object so you can add where, count or attach. attach adds links, detach removes them and sync makes the set exactly the list you pass. Creating through the relation, $book->reviews()->create([...]), fills book_id for you.
The N+1 problem and eager loading
Reading $book->category runs a query the first time. In a loop that means one query for the list plus one per row:
foreach (Book::all() as $b) { $b->category->name; }
foreach (Book::with('category')->get() as $b) { $b->category->name; }Counting the queries with DB::enableQueryLog() and DB::getQueryLog() on three books:
4 queries (lazy)
2 queries (eager)Three books gave 1 + 3 = 4 queries lazily; with('category') loads all needed categories in one extra query. With hundreds of books the difference is large. The names for aggregates also help:
$books = Book::with(['category', 'tags'])->withCount('reviews')->withAvg('reviews', 'rating')->get();That ran three queries for any number of books and added reviews_count and reviews_avg_rating attributes:
The Quiet Harbour | Fiction | 2 tags | 1 reviews | avg 5
Paper Lanterns | Fiction | 0 tags | 0 reviews | avg -
Salt and Signal | Crime | 1 tags | 0 reviews | avg -Filtering by relationships uses has and whereHas: Book::has('reviews')->count() gave 1, and Book::whereHas('tags', fn ($q) => $q->where('slug', 'sea'))->count() gave 2.
Laravel can warn you about accidental lazy loading with Model::preventLazyLoading() in a service provider during development; see the Eloquent relationships chapter of the documentation.
Common mistakes
- Lazy loading in loops and templates, which silently multiplies queries. Eager load what the page needs.
- Putting the relation on the wrong model. The foreign key side is
belongsTo. - Misnamed pivot table. Use alphabetical singular names or pass the table name explicitly.
- Forgetting to import relation return types, or the class used inside them.
- Using
attachwhen you meansync, which creates duplicate-link errors or leaves old links.
Exercise
Show each category with how many books it has using one query for the counts, and print the result. Then write the whereHas call for books tagged cosy.
Show one possible answer
Category::withCount('books')->get()->each(fn ($c) => print("{$c->name}: {$c->books_count}\n"));
Book::whereHas('tags', fn ($q) => $q->where('slug', 'cosy'))->get();With the demo data this prints Fiction: 2 and Crime: 1, and the second query returns The Quiet Harbour. Next: pagination and scopes.
Key points
- A foreign key column such as books.category_id becomes a belongsTo method on Book and a hasMany method on Category.
- Many-to-many links need a pivot table (here book_tag) and belongsToMany on both models, with attach, detach and sync to change links.
- Reading $book->category runs a query the first time; looping over many books this way causes the N+1 query problem.
- with('category') eager loads the related rows in one extra query, and withCount and withAvg add aggregate columns.
- has and whereHas filter models by whether related rows exist.