Home > Laravel > Laravel Many to Many Eloquent Relationship

Laravel Many to Many Eloquent Relationship

Many to Many relationship is a little more complicated than one-to-one and one-to-many relationship, but don’t worry I will cover each and every point so can better understand.

To make the many to many eloquent relationship in laravel, you need three tables. Two tables will have their own data and the third table will have the data of both tables which links each other. You can also say the intermediate table or pivot table.

So in this tutorial, I will show you how to make many to many eloquent relationship and uses cases of getting, inserting, updating, or deleting the records from database tables.

There are more other types of eloquent relationships and each type has a different role of use. All are easy to use but the polymorphic relationship is a bit complicated. But you don’t need to worry about that I will explain in easy ways one by one in laravel tutorial.

Let’s get started!!!

Laravel Many To Many Eloquent Relationship Example

So in this example tutorial, we will create three tables ‘users‘, ‘roles‘, and ‘role_user‘. The ‘role_user‘ table is the pivot table and the name should be alphabetically ordered of related model names.

Why do we need a ‘role_user’ table???

It is a very good question and mostly asked in interviews about this eloquent relationship. So we used the ‘role_user‘ table because we cannot directly add the ‘user_id‘ column in the ‘roles‘ table. If we do that then it would mean a role could only belong to a single user.

So in this tutorial guide, we will use the belongsToMany() method to make a many to many eloquent relationship.

laravel-many-to-many-relationship

So let’s get started with creating a laravel application, migrations, models and then make a many-to-many eloquent relationship.

Create a Laravel Application

First thing you need to create a new laravel application if you don’t have one. So use the following command to install the laravel application.

Note: Make sure you have composer installed on your machine. If it’s not installed then see the full tutorial of laravel installation in more detail.

Create Migrations of Tables

After installation, we will create migration files for the database tables. Let’s create migrations for User, Role, and RoleUser models.

Run the following commands in your terminal to create the migration files. It will create two files in the /database/migrations folder.

Now you have to add the columns in these files as you want. For this tutorial, we are taking the following migration example files for ‘users‘, ‘roles‘, and ‘role_user‘ tables.

You see above we have created the table structure of three tables in migration files. You also may have noticed that we used onDelete('cascade') and references() methods. Basically, the references() method is used to refer the foreign key to another table’s primary key and onDelete(‘cascade’) method is used to delete the relational data.

So after making the changes in migration files, now you have to run the following command to create the database tables using these migration files structures.

Create Models ‘User’, ‘Role’ and ‘RoleUser’

Now let’s create models of User, Role and RoleUser where we will define the eloquent methods respectively. So run the following commands to make models.

After creating the models, let’s define the relational methods in User and Role models to link with each other and the RoleUser model.

In the above model we define the roles() method using the belongsToMany() method that has an argument as a relative model class. Now you can access the roles of users using the roles dynamic property.

Now if you want to get all users that have a specific role then you have to do the same thing in the Role model. See the following code for the Role model.

In this above model, we define the users() method using the belongsToMany() method and passed the first argument as a relative model class.

Note: The belongsToMany() method automatically determine the relationship’s intermediate table name that joins the two table. But if you have a different name for an intermediate table then you can pass the second argument as the intermediate table name.

You can further customize the belongsToMany() method if you had added the different key columns in the RoleUser model. 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.

Now add some dummy data manually that has proper relation between each table or you can use the laravel database seeder feature it will create dummy data for you.

Create ‘MainController’ and Call Methods

Now you have to create a controller to call those methods to get the results accordingly. Use the following commands to create a controller.

The above command will create the controller file like the following. And now you are ready to get the user’s role or user by role by creating the function for API and calling them.

As you notice that in the above controller methods we used the pivot attribute to get the data of the linked table. Actually, this pivot attribute represents the intermediate model and it is automatically assigned when you are getting the data in many to many relationship.

There are more filters with pivot attribute in advance that you can check on the laravel’s official documentation for details.

Create Routes to Get the Records

To create the routes, go to the /routes folder and open the web.php file. In this file, you can create routes for your application. Add the following two routes in this file.

Now you can call these APIs by starting the laravel application using the php artisan serve command and using the following URLs in your browser.

Hope your code will run flawlessly!!!

Conclusion

So in this tutorial, you learned about many to many laravel eloquent relationship to join the three tables each other and one of them has an intermediate table.

You also learned how to create a laravel application, migration, models, and controller to make the many to many eloquent relationship in laravel. And we used the belongsToMany() method in models by passing the argument as a relative model class and more customizations with it.

Photo of author

About Aman Mehra

Hey there! I'm Aman Mehra, a full-stack developer with over six years of hands-on experience in the industry. I've dedicated myself to mastering the ins and outs of PHP, WordPress, ReactJS, NodeJS, and AWS, so you can trust me to handle your web development needs with expertise and finesse. In 2021, I decided to share my knowledge and insights with the world by starting this blog. It's been an incredible journey so far, and I've had the opportunity to learn and grow alongside my readers. Whether you're a seasoned developer or just dipping your toes into the world of web development, I'm here to provide valuable content and solutions to help you succeed. So, stick around, explore the blog, and feel free to reach out if you have any questions or suggestions. Together, let's navigate the exciting world of web development!

Leave a Comment