Lessons → Laravel → Lesson 7

Eloquent Relationships

Laravel
⏱ 30 min read📖 IntermediateNot completed

Relationships define how database tables are connected. Eloquent makes it easy to work with related data using expressive PHP methods.

One to Many (hasMany / belongsTo)

PHP
<?php
// User has many Posts
class User extends Model {
    public function posts() {
        return $this->hasMany(Post::class);
    }
}

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

// Usage
$user = User::find(1);
$posts = $user->posts;        // All posts by this user
$count = $user->posts()->count();

$post = Post::find(1);
$author = $post->user;        // The author of this post
echo $author->name;
?>

One to One (hasOne / belongsTo)

PHP
<?php
class User extends Model {
    public function profile() {
        return $this->hasOne(Profile::class);
    }
}

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

$user = User::find(1);
echo $user->profile->bio;
echo $user->profile->avatar;
?>

Many to Many (belongsToMany)

PHP
<?php
// Post has many Tags, Tag has many Posts
// Requires pivot table: post_tag (post_id, tag_id)

class Post extends Model {
    public function tags() {
        return $this->belongsToMany(Tag::class);
    }
}

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

// Usage
$post = Post::find(1);
$tags = $post->tags;           // All tags for this post

// Attach / detach tags
$post->tags()->attach(1);      // Add tag ID 1
$post->tags()->detach(2);      // Remove tag ID 2
$post->tags()->sync([1, 3, 5]); // Set exactly these tags
?>

Eager Loading (N+1 Prevention)

PHP
<?php
// BAD — N+1 problem (1 query for posts + 1 query per post for user)
$posts = Post::all();
foreach ($posts as $post) {
    echo $post->user->name;  // Runs a new query each time!
}
// With 100 posts = 101 queries!

// GOOD — Eager loading (only 2 queries total)
$posts = Post::with('user')->get();
foreach ($posts as $post) {
    echo $post->user->name;  // No extra queries!
}

// Multiple relationships
$posts = Post::with(['user', 'tags', 'comments.user'])->get();
?>
💡
Always eager load! N+1 is one of the most common performance problems in Laravel apps. Always use with() when you know you'll access related data in a loop.
← Previous Lesson Next Lesson →
🧠

Test your knowledge!

Take a quiz to reinforce what you learned.

Take Quiz →