Laravel 10 Many-to-Many Eloquent Relationship Tutorial

Reading Time: 9 minutes
829 Views

Managing relationships between database tables is a crucial necessity for handling complicated data structures in web application development. The many-to-many relationship, in which several records in one table are related with multiple records in another table, is one of the most versatile and widely used.

In Laravel, a many-to-many Eloquent relationship is a type of relationship between two database tables where each record in the first table can have multiple associated records in the second table, and each record in the second table can also have multiple associated records in the first table.

Laravel, a powerful PHP framework, makes it easier to construct such associations with its Eloquent ORM. In this tutorial, we will walk you through the process of constructing a many-to-many Eloquent connection in Laravel 10, allowing you to manage and retrieve related data from your database more effectively.

Read More: Laravel 10 One to Many Eloquent Relationship Tutorial

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

Open terminal and run this command to create a laravel project.

composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

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 & Database Tables

To get idea about many-to-many relationship you need few migration files,

  • User migration for users table to store user data
  • Role migration for roles table to store roles
  • Role User Migration for role_user table 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 xxx_create_roles_table.php and xxx_create_role_user_table.php inside /database/migrations folder.

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

Read More: Laravel 10 One to One Eloquent Relationship Tutorial

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

<?php

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

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

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

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

<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up(): void
    {
        Schema::create('role_user', function (Blueprint $table) {
            $table->foreignId('user_id')->constrained('users');
            $table->foreignId('role_id')->constrained('roles');
        });
    }

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

Run Migrations

Next, you need to migrate migrations,

php artisan migrate

This command will create tables inside database.

Setup Model with Many-to-Many & Inverse Relationship

Next, you need to create two model classes and also need User model which already exists.

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 and RoleUser.php inside /app/Models folder.

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

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class RoleUser extends Model
{
    use HasFactory;

    protected $table = "role_user";

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = ["user_id", "role_id"];

    public $timestamps = false;
}

Add Many To Many Relationship

Open User.php from /app/Models folder and write this code into it.

<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use App\Models\Phone;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

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

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
    ];

    // Many-to-Many
    public function roles(): BelongsToMany
    {
        return $this->belongsToMany(Role::class, "role_user");
    }
}

$this->belongsToMany(Role::class, “role_user”); This means that a Role can have many users. This is establishing Polymorphic Many-To-Many Relationship.

Read More: Laravel 10 Call MySQL Stored Procedure Example Tutorial

Once the relationship is defined, you may access the user’s roles using the roles dynamic relationship property:

Usage

$user = User::find($user_id)->roles;

Inverse Polymorphic Many-to-Many Relationship

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

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Model;
use App\Models\User;

class Role extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = ["name"];
  
    public $timestamps = false;

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

$this->belongsToMany(User::class, ‘role_user’); This means that a User can have many roles. This is establishing Inverse Polymorphic Many-To-Many Relationship.

Usage

$users = Role::find($role_id)->users;

Next,

How To Use Relations in Laravel Controller?

Let’s test with a dummy application controller class.

Open any controller say DataController.php file from /app/Http/Controllers folder.

Here, you can see two methods in which we used model methods as a property.

<?php

namespace App\Http\Controllers;

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

class DataController extends Controller
{
    // To get all roles of a user
    public function getRoles($user_id)
    {
        return User::find($user_id)->roles;
    }

    // To get all users by role
    public function getUsers($role_id)
    {
        return Role::find($role_id)->users;
    }
}

Explanation,

  • $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

Add Routes

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

//...

use App\Http\Controllers\DataController;

Route::get('get-users/{id}', [DataController::class, 'getUsers']);
Route::get('get-roles/{id}', [DataController::class, 'getRoles']);

//...

Application Testing

Run this command into project terminal to start development server,

php artisan serve

URLs

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

That’s it.

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

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

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.