BHUBAN.DEV
Laravel Tutorials

Mastering Eloquent Database Relationships in Laravel 12

May 22, 2026 6 min read 151 views 0 comments
Mastering Eloquent Database Relationships in Laravel 12

Laravel Eloquent is one of the most powerful Object-Relational Mappers (ORM) in PHP development. In Laravel 12, performance optimizations have made database querying even faster. Understanding how to model database tables is a fundamental skill for building professional systems.

1. One-To-Many Relationships

To declare that a Project Category has many Projects, we declare a `hasMany` method in the category model. On the project side, we declare a `belongsTo` method. This enables Eloquent to fetch records using database index mappings behind the scenes.

public function projects() {\n    return $this->hasMany(Project::class);\n}
2. Lazy vs Eager Loading

By default, Eloquent lazy loads relationships. If you access `$project->category`, it runs a separate SQL query. In loops, this results in the dreaded N+1 Query Problem. By using eager loading via the `with()` method, we consolidate all queries into one optimized SQL SELECT statement.

$projects = Project::with('category')->get();

Using eager loading reduces database connection overhead and can decrease server response time by 50% or more on high-traffic pages.

Tags: #Laravel 12 #Database #PHP #Clean Code

Comments (0)

No comments approved yet. Be the first to share your thoughts!

Leave a Comment