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
<?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.