Eloquent Many-to-Many Relationship in Laravel 10 Tutorial

Share this Article
Reading Time: 8 minutes
118 Views

Inside this article we will see the concept i.e How to define many-to-many relationship in Laravel 10. Article contains the classified information i.e What is Many to Many Relationship and How it works in laravel.

We will see the complete Idea of Best practices for using many-to-many relationships in Laravel 10.

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.

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.

Learn More –

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

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 2023_03_04_015502_create_roles_table.php and 2023_03_04_015803_create_role_user_table.php inside /database/migrations folder.

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

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()
    {
        Schema::create('roles', function (Blueprint $table) {
            $table->id();
            $table->string('name', 25);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        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()
    {
        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()
    {
        Schema::dropIfExists('role_user');
    }
};

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

<?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()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

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

Run Migrations

Next, we need to migrate migrations.

$ php artisan migrate

This command will create tables inside database.

Create Model & Add Relationships

Next, we need to create two models and also we 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 & 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";

    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\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use App\Models\Role;

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',
    ];

    /**
     * The roles that belong to the user.
     */
    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.

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;

    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;

Controller Usage

Now, let’s test with a dummy application controller file.

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

Here, we have created two methods in which we use 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;
    }
}
  • $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

Open project to terminal and type the command 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

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

Buy Me a Coffee

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.