Eloquent Relationships
The core Eloquent relationship types with examples and the N+1 trap to avoid.
~1 min read updated Jul 17, 2026 Laravel
#laravel #eloquent #database #orm
Eloquent relationships map database foreign keys to expressive PHP methods. Get the direction right and most data access reads like plain English.
The common relationships
class Post extends Model
{
public function comments()
{
return $this->hasMany(Comment::class);
}
}
class Comment extends Model
{
public function post()
{
return $this->belongsTo(Post::class);
}
}
class User extends Model
{
public function roles()
{
return $this->belongsToMany(Role::class);
}
}
class User extends Model
{
public function profile()
{
return $this->hasOne(Profile::class);
}
}
The N+1 problem
Accessing a relationship inside a loop fires one query per row. A list of 50
posts that each read their author is 51 queries.
// Bad: 1 query for posts, then 1 per post for the author
$posts = Post::all();
foreach ($posts as $post) {
echo $post->author->name;
}
// Good: 2 queries total, thanks to eager loading
$posts = Post::with('author')->get();
Catch it early
Tell Eloquent to throw when a relationship is lazy-loaded, so N+1 bugs surface in development instead of production:
app/Providers/AppServiceProvider.php
use Illuminate\Database\Eloquent\Model;
public function boot(): void
{
Model::preventLazyLoading(! $this->app->isProduction());
}
Constrain eager loads to only the columns you need:
Post::with('author:id,name')->get().Laravel
The PHP framework for web artisans — Eloquent, routing, queues and more.
Laravel Homestead
My quick reference for setting up and using Laravel Homestead during development.