Blog Post

Laravel Eloquent: Relationships That Make Sense

Transforming database interactions into elegant PHP code

Laravel's Eloquent ORM transforms database interactions into elegant, readable PHP code. Understanding relationships is key to leveraging Eloquent's full power.

One-to-Many: The Most Common Pattern

A user has many posts. A post belongs to one user:

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

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

// Usage
$user = User::find(1);
$posts = $user->posts; // Collection of posts
$author = $post->user; // Single user

Many-to-Many: Tags and Categories

Posts can have many tags, tags can belong to many posts:

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

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

// Usage
$post->tags()->attach($tagId);
$post->tags()->detach($tagId);
$post->tags()->sync([1, 2, 3]);

Polymorphic Relations

When multiple models can have the same relationship. Comments on posts, videos, and photos:

// Comment model
public function commentable() {
    return $this->morphTo();
}

// Post model
public function comments() {
    return $this->morphMany(Comment::class, 'commentable');
}

// Usage
$post->comments()->create(['body' => 'Great post!']);

Eager Loading: Avoiding the N+1 Problem

Loading relationships efficiently prevents performance issues:

// Bad: N+1 queries
$posts = Post::all();
foreach($posts as $post) {
    echo $post->user->name; // Query for each post
}

// Good: 2 queries total
$posts = Post::with('user')->get();
foreach($posts as $post) {
    echo $post->user->name; // No additional queries
}

Advanced Queries

Eloquent relationships support query constraints:

$user->posts()
    ->where('published', true)
    ->orderBy('created_at', 'desc')
    ->take(5)
    ->get();

Eloquent relationships make database interactions intuitive while maintaining performance and flexibility.