Laravel Table Relationship Methods With Example — Phpflow.com

Parvez Alam
2 min readFeb 29, 2024

--

This Laravel tutorial helps to understand table Relationships using Elequonte ORM. We’ll explore laravel table Relationships usage and best practices with examples.

Understanding Laravel Table Relationships

There are the following types of table relationships supported by Laravel:

  • One-to-One
  • One-to-Many
  • Many-to-One (Inverse of One-to-Many)
  • Many-to-Many

Let’s assume you have an “employees” and a “departments” table, and you want to perform a join operation using Laravel’s Eloquent ORM. Define the relationship between Employee and Department models:

namespace App\Models; use Illuminate\Database\Eloquent\Model; class Employee extends Model { public function department() { return $this->belongsTo(Department::class); } } class Department extends Model { public function employees() { return $this->hasMany(Employee::class); } }

One-to-One Relationship

This relationship associated each record in one table with exactly one record in another table.

class Employee extends Model { public function department() { return $this->hasOne(Department::class); } } class Department extends Model { public function employee() { return $this->belongsTo(Employee::class); } }

One-to-Many Relationship:

A one-to-many relationship signifies that each record in one table can be associated with multiple records in another table.

class Department extends Model { public function employees() { return $this->hasMany(Employee::class); } } class Employee extends Model { public function department() { return $this->belongsTo(Department::class); } }

Many-to-Many Relationship:

A many-to-many relationship associates each record in one table with multiple records in another table, and vice versa.

class Employee extends Model { public function departments() { return $this->belongsToMany(Department::class); } } class Department extends Model { public function employees() { return $this->belongsToMany(Employee::class); } }

Employees may belong to multiple departments, and departments may have multiple employees.

Conclusion

The table relationship methods provide a powerful mechanism for managing data associations between database tables. You can define different associations between tables and use the power of Laravel’s Eloquent ORM.

Originally published at https://www.phpflow.com on February 29, 2024.

--

--

Parvez Alam
Parvez Alam

Written by Parvez Alam

Hey, I am Parvez Alam. A software developer since 2009. I love learning and sharing knowledge. https://www.phpflow.com/

No responses yet