loading...

Laravel Eloquent Relationships Tutorial with Examples From Scratch

ellis22 profile image Ellis ・2 min read

The Eloquent ORM that comes with Laravel makes it incredibly easy to interact with a database. It is like Eloquent models themselves; relationships also serve as an essential query builders, representing the relationships as methods provide powerful method chaining and querying capabilities.

Today we'll look at how we can use Eloquent to interact with our database.

How Does Eloquent Work?

A Article model will correspond to a 'articles' table in the database. Since we have convention when creating our models and database tables, we can easily call data from our database.

For example, to get all articles from a 'Article' model, all you would do is Article::all(). Using this function would query the database and generate the proper SQL command. Here are some quick examples:

Description Function
Find all articles Article::all()
Find a record Article::find(id)
Delete a record Article::delete(id)

Types of Eloquent Relationships in Laravel

  • One To One
  • One To Many
  • Many To Many
  • HasOne & HasMany Through
  • Polymorphic Relations

One to One Relationship with Example

One to one relationship is one of basic relationships. For example, a User model would be associated with a Address model. To illustrate this relationship, we can create a address() method within the User model and call the hasOne() method to relate the Address model.

One to Many Relationship Example

One of many relationships determines a relationship where one single model owns the number of the other model. For example, a blog author may have many post.

Many to Many Relationship Example

Each post have many tag and each tag can have many post.To define many to many relationships, we use belongsToMany() method.

Adding & Retrieving Pivot Table Columns in Many To Many Relations

Handle events on attach, detach or sync in Many To Many Relations

HasMany Through

The “has-many-through” relationship provides a convenient shortcut for accessing distant relations via an intermediate relation. For example, a Country model might have many Post models through an intermediate User model. In this example, you could easily gather all blog posts for a given country. Let’s look at the tables required to define this relationship:

has-many-through relation using Pivot model

Polymorphic Relationship

A polymorphic relationship is where a model can belong to more than one other model on a single association.

One to Many & One to One Polymorphic Relationships

Many to Many Polymorphic Relationship

Discussion

pic
Editor guide
Collapse
mzwandiled profile image
Mzwandile Lucky Dladla

great tutorials man thanks, they are on point and easy to follow through