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:
class User extends Model
{
public function profile()
{
return $this->hasOne(Profile::class);
}
}
$user = User::find(1);
$profile = $user->profile;
class User extends Model
{
public function posts()
{
return $this->hasMany(Post::class);
}
}
$user = User::find(1);
$posts = $user->posts;
class User extends Model
{
public function roles()
{
return $this->belongsToMany(Role::class);
}
}
class Role extends Model
{
public function users()
{
return $this->belongsToMany(User::class);
}
}
$user = User::find(1);
$roles = $user->roles;
$role = Role::find(1);
$users = $role->users;
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');
}
}
$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.