Eloquent ORM is one of Laravel's greatest strengths. Understanding relationships deeply helps you write efficient queries and avoid N+1 performance traps.
Core Relationship Types
- hasOne / hasMany — parent-to-child ownership (User → Posts)
- belongsTo — inverse of hasMany (Post → User)
- belongsToMany — pivot tables for tags, roles, and categories
- morphMany / morphTo — comments on posts, videos, or any model
Eager Loading
Always use with() when listing related data. Replace dozens of queries with one:
Post::with(['author', 'comments.user'])->published()->paginate(10);
Query Constraints
Filter relationships inline with closures — e.g. only active comments or recent orders — without writing raw SQL.
Best Practices
- Define inverse relationships for bidirectional access.
- Use
withCount()for aggregates instead of loading full collections. - Index foreign keys on large tables.