In Laravel, Eloquent relationships are a powerful feature that allows you to define the associations between different database tables and models.
Eloquent provides an elegant and expressive syntax to define relationships, making it easy to work with related data in your application.
There are several types of relationships in Laravel:
- One-to-One Relationship
- One-to-Many Relationship
- Many-to-Many Relationship
- Has Many Through Relationship
- Polymorphic Relationships
1. One-to-One Relationship:
In a one-to-one relationship, each record in a table is associated with exactly one record in another table.
Example: User has one Profile
// User Model
class User extends Model
{
public function profile()
{
return $this->hasOne(Profile::class);
}
}
// Profile Model
class Profile extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
2. One-to-Many Relationship:
In a one-to-many relationship, a single record in one table can be associated with multiple records in another table.
Example: User has many Posts
// User Model
class User extends Model
{
public function posts()
{
return $this->hasMany(Post::class);
}
}
// Post Model
class Post extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
3. Many-to-Many Relationship:
In a many-to-many relationship, records in one table can be associated with multiple records in another table, and vice versa.
Example: User belongs to many Roles, and Role belongs to many Users
// User Model
class User extends Model
{
public function roles()
{
return $this->belongsToMany(Role::class);
}
}
// Role Model
class Role extends Model
{
public function users()
{
return $this->belongsToMany(User::class);
}
}
4. Has Many Through Relationship:
This relationship is used to define a relationship with a third intermediate model.
Example: Country has many Posts through User
// Country Model
class Country extends Model
{
public function posts()
{
return $this->hasManyThrough(Post::class, User::class);
}
}
5. Polymorphic Relationships:
Polymorphic relationships allow a model to belong to more than one type of another model on a single association.
Example: Comment can belong to both Post and Video
// Comment Model
class Comment extends Model
{
public function commentable()
{
return $this->morphTo();
}
}
// Post Model
class Post extends Model
{
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
}
// Video Model
class Video extends Model
{
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
}