Laravel 8 Many to Many Eloquent Relationship Tutorial

Reading Time: 10 minutes
25,181 Views

Laravel eloquent relationship is a very important feature which connects one or more tables in a chain. This is the substitute of joins in laravel.

Laravel provides these following relationships –

Eloquent relationships are defined as methods on your Eloquent model classes. Inside this article we will see the concept of laravel 8 Many to Many Eloquent relationship as well as we will implement inverse of many to many relationship i.e belongsToMany.

This article will give you the detailed concept of about implementation of many to many relationship in laravel.

For this tutorial we will consider a users table, roles table and role_user table. This means a single user have multiple roles and a role have multiple users. Means many to many relationship.

Let’s get started.


Laravel Installation

We will create laravel project using composer. So, please make sure your system should have composer installed. If not, may be this article will help you to Install composer in system.

Here is the command to create a laravel project-

composer create-project --prefer-dist laravel/laravel blog

To start the development server of Laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.


Create Database & Connect

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE laravel_app;

To connect database with application, Open .env file from application root. Search for DB_ and update your details.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_app
DB_USERNAME=root
DB_PASSWORD=root

Create Migrations

We need few migration files –

  • User migration to store user data
  • Role migration to store roles
  • Role User Migration to store user id and role id

Open project into terminal and run these artisan commands.

$ php artisan make:migration CreateRolesTable

$ php artisan make:migration CreateRoleUserTable

It will create two migration files 2021_04_03_042735_create_roles_table.php and 2021_04_03_042802_create_role_user_table.php at location /database/migrations.

Already we have 2014_10_12_000000_create_users_table.php migration available by default which is for users table.

Open 2021_04_03_042735_create_roles_table.php and write this complete code into it.

#RoleMigration

Open 2021_04_03_042802_create_role_user_table.php and write this complete code into it.

#RoleUserTable

Also If we open users migration, we should like this.

#UserMigration

Run Migrations

Next, we need to create tables inside database.

$ php artisan migrate

This command will create tables inside database.


Create Model

Next, we need to create two models and already we have a User model. Back to terminal and run these artisan commands.

$ php artisan make:model Role

$ php artisan make:model RoleUser

These commands will create two files Role.php & RoleUser.php at /app/Models folder.

Open Role.php and write this complete code into it.

Role.php

Open RoleUser.php and write this complete code into it.

RoleUser.php

Also If we open User model, copy and paste this complete code into it.

User.php
  • $this->belongsToMany(Role::class, ‘role_user’); It indicates many to many relationship use role_user table
  • If we want to use class instead of table name in the above method, use like this $this->belongsToMany(Role::class, RoleUser::class);

Sample Data Insertion

Open mysql and run these queries to insert dummy data into posts and comments table.

Data for Users Table

Users Table

Data for Roles Table

Roles Table

Data for Role User Table

Role User Table

Calling Methods at Controller

Open any controller say SiteController.php file, we have created two methods in which we used model methods as a property.

#Controller
  • $roles = User::find($user_id)->roles; It will find all roles on the basis of user id. Many to Many
  • $users = Role::find($role_id)->users; It will find all users by role id. Inverse of Many to Many / Belongs To

Create Routes

Open web.php from /routes folder and add these routes into it.

web.php

Application Testing

Run this command into project terminal to start development server,

php artisan serve

Get Users by role id – http://127.0.0.1:8000/get-users/1

Get Roles by user id– http://127.0.0.1:8000/get-roles/1

We hope this article helped you to learn about Laravel 8 Many to Many Eloquent Relationship Tutorial in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.