Eloquent Relationships Cheat Sheet

Mahmoud Zalt
HackerNoon.com
6 min readOct 2, 2017

--

A cheat sheet for Laravel’s Eloquent ORM version 5.5.

One to One Relationship

Demo details:

In this demo we have 2 models (Owner and Car), and 2 tables (owners and cars).

Business Rules:

The Owner can own one Car.
The Car can be owned by one Owner.

Relations Diagram:

Relationship Details:

The Cars table should store the Owner ID.

Eloquent Models:

Database Migrations:

Store Records:

Retrieve Records:

One to Many Relationship

Demo details:

In this demo we have 2 models (Thief and Car), and 2 tables (thieves and cars).

Business Rules:

The Thief can steal many Cars.
The Car can be stolen by one Thief.

Relations Diagram:

Relationship Details:

The Cars table should store the Thief ID.

Eloquent Models:

Database Migrations:

Store Records:

Retrieve Records:

Polymorphic One to Many Relationship

Demo details:

In this demo we have 3 models (Man, Woman and Car), and 3 tables (men, women and cars).

Business Rules:

The Man (buyer) can buy many Cars.
The Woman (buyer) can buy many Cars.
The Car can be bought by one buyer (Man or Woman).

Relations Diagram:

Relationship Details:

The Car table should store the Buyer ID and the Buyer Type.
“buyer” is a name given to a group of models (Man and Woman). And it’s not limited to two. The buyer type is the real name of the model.

Eloquent Models:

Database Migrations:

Store Records:

Retrieve Records:

Many to Many Relationship

Demo details:

In this demo we have 2 models (Driver and Car), and 3 tables (drivers, cars and a pivot table named car_driver).

Business Rules:

The Driver can drive many Cars.
The Car can be driven by many Drivers.

Relations Diagram:

Relationship Details:

The Pivot table “car_driver” should store the Driver ID and the Car ID.

Eloquent Models:

Database Migrations:

Store Records:

Retrieve Records:

Polymorphic Many to Many Relationship

Demo details:

In this demo we have 3 models (Valet, Owner and Car), and 4 tables (valets, owners, cars and drivers).

Business Rules:

The Valet (driver) can drive many Cars.
The Owner (driver) can drive many Cars.
The Car can be driven by many drivers (Valet or/and Owner).

Relations Diagram:

Relationship Details:

The Pivot table “drivers” should store the Driver ID, Driver Type and the Car ID.
“driver” is a name given to a group of models (Valet and Owner). And it’s not limited to two. The driver type is the real name of the model.

Eloquent Models:

Database Migrations:

Store Records:

Retrieve Records:

Follow me on Twitter Mahmoud Zalt.

--

--