Laravel Many To Many Relationship Example From Scratch

I will write on Laravel Many To Many Relationship Example From Scratch.

Laravel’s ORM eloquent concept supports several types of relationship between two or more tables of the database.

Some of them are one to one, one to many or many to many. I will cover many to many relationship today.

Laravel Many To Many Eloquent Relationship

Many to many relationship means that multiple rows of two tables have relationship between each other.

For example, consider a website and it’s users. Users can have roles like admin, editor and reader . To manage this scenario  there are two tables : users and models

users table includes the rows with informations like user_id and name while roles table have columns like id and role_name

Now, one user can play many roles like admin, editor and reader. Similarly, one role can be played by more than one user, Thus it is many to many relationship.

See the below image for more details.

Laravel Many To Many Relationship

As you can see, three tables are there.

Orange arrows clearly shows that one user (John) have played three roles and one role (Reader) is played by three users.

Thus, this is the example of laravel many to many relationship.

Pivot Table

Pivot table is something like an agent or mediator table which manages the many to many relationship between two tables.

Here in above image, role_user tables manages the many to many relationship between users and roles. This called pivot table.

Name of the pivot table should consist of singular names of both tables, separated by undeRscore symbol and these names should be arranged in alphabetical order.

Before we make practical example, consider the following result of this example tutorial.

 

Step 1. Basic Configuration

For creating a new project, new need to run the below command in your terminal,

Now, we need to connect this newly created laravel project with the database.

Go to your database administration tool ( sequel pro, phpMyAdmin etc. ) and make a new database and give it a name “laramanytomany

To connect database and laravel project each other, we should change the .env file of project.

Open your editor and change the below lines in .env file.

Various fields are host number, port number, database name, username, password etc.

Change these fields as per your computer configurations and now you have connected your database and laravel project.

Step 2. Making Roles and Pivot Table

In this example, we will use total of three tables. One table users will be defined by laravel system automatically, so we neede to create two tables manually, one is roles and another is role_user

Run the following command in the terminal

After this, run below command in the terminal

After successful execution of both of these commands, system will create two migration files.

Go to database->migrations directory and open timestamp_create_roles_table.php file.

Write down the below source code in timestamp_create_roles_table.php file.

This migration file is for roles table. up() function in the above file includes the column names for roles table.

Now in the same directory, there is another migration called timestamp_create_role_user_table.php file.

Following is the source snippet for timestamp_create_role_user_table.php file.

Same as previous migration file, up() method have column names for role_user table.

A column user_id is referencing id from the users table.

While role_id is representing the id from the roles table.

Now run the below command in terminal.

This command will create tables like users, roles, role_user, migrations etc.

Step 3. Writing Models

We require three model classes in this example.

Model for users table User.php is already created by system. We will create other two like Role.php and UserRole.php

Before that, let us first add some required lines in User.php file ( app->User.php ).

Final source code for User.php file should be like the below

I have added roles() function in the above file. Other functions are already written by laravel system.

roles() function includes belongsToMany() method. This method is telling compiler that a roles table’s row can have relationship with multiple rows of users table.

Here,  belongsToMany() method is taking the help of pivot table role_user to define many to many relationship.

Now let us create necessary model file. Run the following command first,

It will make a new model file Role.php

Open Role.php which is located at app->Role.php and add the following source snippet in it

Read the users() functions in above code.

It also includes the belongsToMany() method. This method is defining many to many relationship of users table using the Pivot table role_user.

Now run the below command

It will make a model named “UserRole.php” and code for this file is as the following

Step 4. Adding Rows in Database

Let us some records in our database. Just see the below image and add rows as per the image.

Laravel Many To Many Relationship

 

In the above image, users table is located at the top. Middle table is pivot table, role_user and at the bottom there is roles table.

Add three user names John, Ronald and Gary in users table.

Insert three roles as Admin, Editor and Reader in roles table.

Pivot table role_user consists the relationship data between users and roles tables. It uses user_id and role_is to define many to many relationship between these two tables.

Step 5. Making New Controller and Route

Navigate to routes->web.php file and add the below line in it

When user run http://127.0.0.1:8000/manyrole URL in browser, system will trigger the above route.

This route will call manyRoles() method from ManyController.php file.

Now let us make a controller file ManyController.php

First of all, run the below command

You will find a ManyController.php file inside app->Http->Controllers directory after triggering above command.

Write the following source lines in ManyController.php file

Only one function manyRoles() is there.

First line in this function will fetch all the rows from the roles table which is played by the user_id = 1 in pivot table.

Similarly, second line will get all the records from users table who have played role_id = 3 in pivot table.

For more understandings, see the above image which have all three tables one by one.

At last, function will return the compiler to the view file called “index.blade.php” along with two variables.

Step 6. Blade File and Done

Our last step is to create blade view file.

Go to resources->views directory and make a new file index.blade.php

Write down the following code snippet in this view file.

We are using those two variables which we have passed in the return statement in manyRoles() function of controller file.

two foreach loops are created using these variables.

In every iteration of first foreach loop, we will print role name. Similarly, in the second foreach loop , system will print the role name in every iteration.

So, it was all about laravel many to many relationship tutorial with example.

You can also read : laravel one to one relationship tutorial and laravel one to many relationship tutorial

Download Code For Laravel Many To Many Relationship

Click me to get laravel source code

Hardik Parsania

I am mobile app developer. I am always passionate about solving complex and real world problems.I have developed many apps with great interest and superior logical skills.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *