laravel many to many relationships

Demonstrating Laravel Many To Many Relationship

Laravel simplifies manipulating relationships in a very easy way using the eloquent ORM and in this article we will implement the many to many relationship using a simple example.

 

 

As we already know there are three main types of mysql relationships which are (One To OneOne To ManyMany To Many). For manipulating the first two relationships in laravel this is so simple as you have to add methods such as belongsTo() and hasMany() that describe the relations between the models for example if we imagine that we have a database that have two tables users and posts and each user can create many posts and the post belong only to single user so to describe this relation in laravel models:

app>User.php

app>Post.php

In contrast for manipulating many to many relations typically we must have three tables [The first table – the second table – the pivot table (which is the table connecting the two tables by adding each primary key of the first and second tables)]. In laravel to describe such relationship we use method called belongsToMany().

Let’s take an example of an ecommerce website where we have categories and brands tables like the Clothes category may belong to multiple brands like Addidas, Dubles,etc. and in the other hand the Addidas brand may belong to other category such as Electronic devices category so the category has many brands andĀ brands belongs to many categoriesĀ so to implement such relationship let’s consider we have category and brand:

app>Category.php

app>Brand.php

As you see above i have added two methods on both models and each method should return belongsToMany() results of the other model so for categories we have method brands() that return belongsToMany(‘App\Brand’) and for brands we have method categories() that return belongsToMany(‘App\Category’), this tells laravel that this is a many to many relation between categories and brands.

Now to retrieve the brands for specific category we can do this:

To retrieve the categories for specific brand we can do this:

You can chain query methods like this:

 

Customizing the pivot table name and foreign keys

The belongsToMany() method automatically determine the name of the joining table using the alphabetical order of the two related tables but if you want to override this behavior by passing a second argument to belongsToMany() with the table name like this:

Also you can customize the foreign key names by passing two more arguments to belongsToMany(). The third argument is the foreign key name of the model on which you are defining the relationship, while the fourth argument is the foreign key name of the model that you are joining to like this:

app>Category.php

app>Category.php

 

Share this: