Laravel Many To Many Relationship Example From Scratch

Laravel One To Many Relationship, laravel many to many relationship, laravel hasmanythrough, laravel one to many polymorphic, laravel one to one polymorphic, Laravel Many To Many Polymorphic Tutorial Example, laravel hasonethrough, Laravel PDF Generator

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,

laravel new laramanytomany

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.

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

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

php artisan make:migration create_roles_table

After this, run below command in the terminal

php artisan make:migration create_role_user_table

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.

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateRolesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('roles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('role_name');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('roles');
    }
}

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.

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateRoleUserTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('role_user', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('user_id')->unsigned();
            $table->integer('role_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')
                ->onDelete('cascade');
            $table->foreign('role_id')->references('id')->on('roles')
                ->onDelete('cascade');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('role_user');
    }
}

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.

php artisan migrate

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

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * The roles that belong to the user.
     */
    public function roles()
    {
        return $this->belongsToMany(Role::class, 'role_user');
    }

}

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,

php artisan make:model Role

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

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    //
    /**
     * The users that belong to the role.
     */
    public function users()
    {
        return $this->belongsToMany(User::class, 'role_user');
    }
}

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

php artisan make:model UserRole

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

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class UserRole extends Model
{
    //
}

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

Route::get('manyrole','ManyController@manyRoles');

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

php artisan make:controller ManyController

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

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use App\Role;

class ManyController extends Controller
{
    //
    public function manyRoles()
    {
 
        $user = User::find(1);
        $role = Role::find(3);
    
        return view('index',compact('user','role'));
       
    }
}

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.

<html>
<head>
   
</head>
<style>
 
 
</style>
<body>
 
<h1> Laravel Many to Many Example </h1>
<h2> User 1 (John) is playing below Roles

@if ($user->roles->count() > 0)

  <ul>

  @foreach($user->roles as $records)

    <li>{{ $records->role_name }}</li>

  @endforeach

  </ul>

@endif

<h2> Role 3 (Reader) is played by below Users

@if ($role->users->count() > 0)

  <ul>

  @foreach($role->users as $records)

    <li>{{ $records->name }}</li>

  @endforeach

  </ul>

@endif

</body>
</html>

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