Why Relationships Matter
Real databases are full of related data. A user has posts, a post has comments, a comment belongs to a user. Eloquent models these relationships as methods, making it easy to traverse your data without writing JOINs.
One-to-One: hasOne
A one-to-one relationship means one record is directly related to one other record. For example, a User has one Profile:
class User extends Model
{
public function profile()
{
return $this->hasOne(Profile::class);
}
}
Access it like a property:
$profile = $user->profile;
echo $profile->bio;
Try it Yourself โ
One-to-Many: hasMany
A user can have many posts. Define this relationship with hasMany:
class User extends Model
{
public function posts()
{
return $this->hasMany(Post::class);
}
}
Retrieve all posts for a user:
$posts = $user->posts;
foreach ($posts as $post) {
echo $post->title;
}
Inverse: belongsTo
Every hasMany has an inverse. A Post belongs to a User:
class Post extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
Now you can access the user from a post:
echo $post->user->name;
Many-to-Many: belongsToMany
When both sides can have multiple records โ like users and roles โ use belongsToMany. This requires a pivot table:
class User extends Model
{
public function roles()
{
return $this->belongsToMany(Role::class);
}
}
Eloquent expects a role_user pivot table with user_id and role_id columns.
Through Relationships
Sometimes you need to access a distant relationship. A Country has many Posts through Users. Use hasManyThrough:
class Country extends Model
{
public function posts()
{
return $this->hasManyThrough(Post::class, User::class);
}
}
Now $country->posts gives you all posts from users in that country.