Eloquent Relationships
Introduction
Database tables are often related to one another. For example, a blog post may have many comments, or an order may belong to the user who placed it. Eloquent makes managing and working with these relationships easy and supports several common relationships:
- One To One
- One To Many
- Many To Many
- Polymorphic Relations
One To One
A one-to-one relationship is a very basic type of database relationship. For example, a User model might be associated with one Phone model. To define this relationship, place a phone method on the User model:
// app/Models/User.php
public function phone()
{
return $this->hasOne(\App\Models\Phone::class);
}
Defining the Inverse (BelongsTo)
To define the inverse relationship on the Phone model, define a user method that calls the belongsTo method:
// app/Models/Phone.php
public function user()
{
return $this->belongsTo(\App\Models\User::class);
}
One To Many
A one-to-many relationship is used to define relationships where a single model is the parent to one or more child models. For example, a blog post may have an infinite number of comments:
// app/Models/Post.php
public function comments()
{
return $this->hasMany(\App\Models\Comment::class);
}
// Accessing comments:
$comments = Post::find(1)->comments;
On the child model, define the inverse using belongsTo:
// app/Models/Comment.php
public function post()
{
return $this->belongsTo(\App\Models\Post::class);
}
Many To Many
Many-to-many relations are slightly more complicated than hasOne and hasMany relationships. An example of a many-to-many relationship is a user that has many roles, while those roles are also shared by other users.
To define this relationship, three database tables are needed: users, roles, and role_user (the intermediate pivot table):
// app/Models/User.php
public function roles()
{
return $this->belongsToMany(\App\Models\Role::class);
}
// Accessing roles:
$user = User::find(1);
foreach ($user->roles as $role) {
echo $role->name;
}
Attaching & Detaching Pivot Records
// Attach a role to a user
$user->roles()->attach($roleId);
// Detach a role
$user->roles()->detach($roleId);
// Sync roles (replaces existing associations)
$user->roles()->sync([1, 2, 3]);
Polymorphic Relationships
A polymorphic relationship allows the child model to belong to more than one type of model using a single association. For example, users of your application can "comment" on both posts and videos:
// app/Models/Comment.php
public function commentable()
{
return $this->morphTo();
}
// app/Models/Post.php
public function comments()
{
return $this->morphMany(\App\Models\Comment::class, 'commentable');
}
// app/Models/Video.php
public function comments()
{
return $this->morphMany(\App\Models\Comment::class, 'commentable');
}
Next Steps
- Eliminate slow queries with Eager Loading.
- Explore full-text search with DataTable Pattern.
- Inspect relationship diagrams visually in ArgusKit Studio.