Eloquent makes defining and querying relationships between tables straightforward, without writing joins by hand.
class User extends Model
{
public function posts()
{
return $this->hasMany(Post::class);
}
}
class Post extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
public function tags()
{
return $this->belongsToMany(Tag::class); // many-to-many, uses a pivot table
}
public function comments()
{
return $this->hasMany(Comment::class);
}
}
Usage:
$user->posts; // Collection of the user's posts (lazy-loaded on first access)
$post->user->name; // The post's author name
$post->tags()->attach($tagId); // Attach a many-to-many relation
The N+1 query problem: looping over posts and accessing $post->user->name inside the loop triggers one query per post. Fix it with eager loading:
$posts = Post::with('user', 'comments')->get(); // just 3 queries total, not N+1
Other relationship types include hasOne, hasManyThrough, and polymorphic relations (morphTo/morphMany) for cases like comments that can belong to either a Post or a Video. Laravel Debugbar or DB::enableQueryLog() are handy for spotting N+1 issues during development.