PHP & Laravel Sanjay Gupta June 11, 2026 9 views
Mastering Laravel Eloquent Relationships

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

  1. Define inverse relationships for bidirectional access.
  2. Use withCount() for aggregates instead of loading full collections.
  3. Index foreign keys on large tables.