Overview
Database tables are often related to one another. A blog post has many comments; an order belongs to a user. Eloquent makes it easy to define these relationships and query related data in a natural, expressive way. Relationships are defined as methods on your Eloquent model classes.Examples on this page use
User, Post, Comment, and Tag models. Assume these models and their database tables already exist.hasOne (one-to-one)
UsehasOne when a model owns exactly one related model. For example, a User has one Profile.
Defining the relationship
profiles table has a user_id foreign key based on the parent model name.
Accessing the related model
Access the relationship as a property — Eloquent queries the database automatically:belongsTo (inverse of hasOne)
belongsTo is the inverse of hasOne. Define it on the model that holds the foreign key — in this case, Profile belongs to User.
_id as the foreign key (user_id).
hasMany (one-to-many)
hasMany is the most common relationship type. Use it when a parent model owns multiple child models — for example, a Post has many Comment records.
Defining the relationship
comments table has a post_id foreign key.
Accessing related records
AhasMany relationship returns a collection:
Inverse relationship
To navigate from a comment back to its post, definebelongsTo on Comment:
belongsToMany (many-to-many)
Use a many-to-many relationship when both models can be associated with multiple instances of each other. For example, aPost can have many Tag records, and a Tag can belong to many posts.
Table structure
Many-to-many relationships require a pivot table. ForPost and Tag, create a post_tag pivot table:
Eloquent infers the pivot table name by alphabetically combining the two model names:
post + tag → post_tag.Defining the relationship
Tag to navigate in both directions:
Retrieving related records
Attaching and detaching
Useattach() to add a record to the pivot table, detach() to remove one:
Eager loading
The N+1 problem
When you access a relationship as a property, Eloquent runs a separate query each time. Inside a loop this creates an N+1 problem:Eager loading with with()
Use with() to load all related data in just two queries:
Loading multiple relationships
Pass an array to eager-load several relationships at once:Nested eager loading
Use dot notation to eager-load nested relationships:Next steps
Authentication
Learn how to add login and registration to your Laravel application.