How to define and use relationships between Eloquent models in Laravel?

In Laravel, relationships between Eloquent models are defined using methods within the model classes. There are several types of relationships that can be defined, such as one-to-one, one-to-many, many-to-many, and polymorphic relationships.

To define a relationship, you need to specify the relationship type and the related model. You can then use this relationship to query and retrieve related records.

Here's an example of how to define and use relationships between Eloquent models in Laravel:

  1. One-to-One Relationship:
    • Define the relationship in the model class:
class User extends Model { public function profile() { return $this->hasOne(Profile::class); } }
  • Use the relationship to retrieve related records:
$user = User::find(1); $profile = $user->profile;
  1. One-to-Many Relationship:
    • Define the relationship in the model class:
class User extends Model { public function posts() { return $this->hasMany(Post::class); } }
  • Use the relationship to retrieve related records:
$user = User::find(1); $posts = $user->posts;
  1. Many-to-Many Relationship:
    • Define the relationship in both model classes:
class User extends Model { public function roles() { return $this->belongsToMany(Role::class); } } class Role extends Model { public function users() { return $this->belongsToMany(User::class); } }
  • Use the relationship to retrieve related records:
$user = User::find(1); $roles = $user->roles; $role = Role::find(1); $users = $role->users;
  1. Polymorphic Relationship:
    • Define the relationship in the model class using a special morphTo method and morphMany or morphOne methods for the related models:
class Comment extends Model { public function commentable() { return $this->morphTo(); } } class Post extends Model { public function comments() { return $this->morphMany(Comment::class, 'commentable'); } } class Video extends Model { public function comments() { return $this->morphMany(Comment::class, 'commentable'); } }
  • Use the relationship to retrieve related records:
$post = Post::find(1); $comments = $post->comments; $video = Video::find(1); $comments = $video->comments;

These are just some of the relationships that can be defined and used in Laravel. The framework provides many more options and methods to handle complex relationships between Eloquent models.