BuildBot

Laravel in a Container

Relationships & queries

Lesson 4 of 4

What you'll learn

  • Define a one-to-many relationship in Eloquent
  • Build queries with the fluent builder
  • Recognize and fix the N+1 query problem with eager loading

Real data is connected. A User has many Posts; a Post belongs to a User. Eloquent expresses that as methods on the model:

class User extends Model {
    public function posts() { return $this->hasMany(Post::class); }
}

class Post extends Model {
    public function user() { return $this->belongsTo(User::class); }
}

$user = User::find(1);
$user->posts;        // a collection of that user's posts
$post->user->name;   // walk back to the author

Building queries

The query builder is chainable and reads like a sentence. It compiles to parameterized SQL — safe from injection:

$recent = Post::where('published', true)
    ->orderBy('created_at', 'desc')
    ->limit(10)
    ->get();

The N+1 trap

Loop over 50 posts and access $post->user on each, and you fire 51 queries — one for the posts, then one per post for its user. Eager load the relationship to collapse it to two:

$posts = Post::with('user')->get(); // posts + their users in 2 queries

Watch for N+1

N+1 is the most common Laravel performance bug. If a page gets slow as data grows, look for a relationship accessed inside a loop and add ->with(...).

The challenge is a chainable query builder that compiles to SQL — the shape of Eloquent's builder. Run it.

Eloquent's builder, compiled to SQL

Each method appends to the query; toSql() emits it. Run it, then add another where().

Loading editor…

That's the loop: containers up, requests routed, schema migrated, data modeled and queried. You can now read and reason about a Dockerized Laravel + Postgres app — and you've got runnable models of the pieces to come back to.

Sign in to save your progress across devices.