Eloquent ORM: Relationships in Laravel

Eloquent ORM (Object-Relational Mapper) in Laravel provides a simple and elegant way to interact with your database using models.

One of its most powerful features is the ability to define relationships between different models, making it easier to manage and query related data.

 

Types of Relationships

One-to-One

A one-to-one relationship is used to define a single record in one table that is associated with a single record in another table.

Example:

<?php
// User model
public function phone(){
    return $this->hasOne(Phone::class);
}
// Phone model
public function user(){
  return $this->belongsTo(User::class);
}
You can access the related phone record like this:
<?php
$user = User::find(1);
$phone = $user->phone;

One-to-Many

A one-to-many relationship is used to define a single record in one table that is associated with multiple records in another table.

Example:

<?php
// Post model
public function comments(){
    return $this->hasMany(Comment::class);
}
// Comment model
public function post(){
    return $this->belongsTo(Post::class);
}
You can access the related comments like this:
<?php
$post = Post::find(1);
$comments = $post->comments;

Many-to-Many

A many-to-many relationship is used to define records in one table that are associated with multiple records in another table and vice versa.

Example:

<?php

// User model

public function roles(){

return $this->belongsToMany(Role::class);

}

// Role model

public function users(){

    return $this->belongsToMany(User::class);

}

You can access the related roles like this:

<?php

$user = User::find(1);

$roles = $user->roles;

 

Has Many Through

A “has many through” relationship provides a convenient shortcut for accessing distant relations via an intermediate relation.

Example:

<?php
// Country model
public function posts(){
    return $this->hasManyThrough(Post::class, User::class);
}
You can access the posts related to a country like this:
<?php
$country = Country::find(1);
$posts = $country->posts;

Read Also :-

Using Query ID in Elementor for Custom Post Filtering

How to Setup Daily and Weekly Backup Cron on Linux server

Also Visit:-

https://inimisttech.com/

Leave a Reply