agyanadda@gmail.com

Laravel Eloquent Relationships

Database and Eloquent 1 min read Updated Dec 2, 2026 Topic 10 of 13

Real data is connected: a user writes many posts, a post has many comments, a post has many tags. Eloquent relationships let you move between them with simple methods.

One-to-many

  • In User: public function posts() { return $this->hasMany(Post::class); }
  • In Post: public function user() { return $this->belongsTo(User::class); }

The posts table needs a user_id column.

Many-to-many

A post has many tags and a tag belongs to many posts. Use belongsToMany on both models and a pivot table named post_tag with post_id and tag_id. Add links with $post->tags()->attach($tagId) or sync([...]).

Using relationships

  • $user->posts — a collection of the user's posts
  • $post->user->name — the author's name
  • $user->posts()->create([...]) — create a post linked to the user

Eager loading (avoid N+1)

Looping over 50 posts and reading $post->user runs 51 queries. Post::with('user')->get() loads everything in 2 queries.

Example

Example — User has many posts PHP
<?php
// app/Models/User.php
public function posts()
{
    return $this->hasMany(Post::class);
}

// app/Models/Post.php
public function user()
{
    return $this->belongsTo(User::class);
}

// Controller: load posts with their authors in 2 queries
$posts = Post::with('user')->latest()->get();

foreach ($posts as $post) {
    echo $post->title . ' by ' . $post->user->name . PHP_EOL;
}

Output is one line per post, e.g. "Hello Eloquent by Asha". with('user') prevents a separate query for every author.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which relationship does a Post use to get its author?

Exercise 2 True / False

Post::with('user') helps avoid the N+1 query problem.

Exercise 3 Fill in the Blank

Many-to-many relationships use the ___ method on both models.

Frequently Asked Questions

$user->posts (a property) runs the query and returns the results. $user->posts() (a method) returns the relationship query, so you can add conditions like ->where('is_published', true)->get() or call ->create().