Updated 4 October 2023
So in this article, we will learn how to use Many To Many Relationships in Laravel. Let’s consider an example to understand this concept better:
The relationship between users and roles. In a many-to-many relationship, a user can be associated with multiple roles, and each role can be linked to multiple users.
To illustrate further, let’s imagine a scenario where a web application manages user accounts. Each user can have various roles, such as “Admin,” “Moderator,” or “Subscriber.” At the same time, each role can be assigned to multiple users, meaning several users may have the “Admin” role, and several others may have the “Moderator” role, and so on.
In this example, We will create “users”, “roles” and “role_user” tables to create many to many relationships with each other by using the Laravel Eloquent Model.
1 |
composer create-project laravel/laravel --prefer-dist laravel |
Laravel already provides the migration and model for the “users” table, So we need to create migration and model only for the “Roles” table. And one another migration for the “role_user” pivot table.
Create a Role model with migration.
1 |
php artisan make:model Role -m |
The above command will create a Role model inside the app/Models folder and a migration file inside the database/migration folder.
Create a migration for role_user Pivot Table.
1 |
php artisan make:migration create_role_user_table |
The above command will create a migration file for the role_user pivot table inside the database/migration folder.
Now you can update your User model, Role model, and migration files accordingly as below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsToMany; class User extends Model { /** * The roles that belong to the user. */ public function roles(): BelongsToMany { return $this->belongsToMany(Role::class); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsToMany; class Role extends Model { /** * The users that belong to the role. */ public function users(): BelongsToMany { return $this->belongsToMany(User::class); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('roles', function (Blueprint $table) { $table->id(); $table->string('name'); $table->timestamps(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('roles'); } }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('role_user', function (Blueprint $table) { $table->foreignId('user_id')->constrained()->onDelete('cascade'); $table->foreignId('role_id')->constrained()->onDelete('cascade'); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('role_user'); } }; |
1 2 3 |
php artisan make:seeder UsersTableSeeder php artisan make:seeder RolesTableSeeder |
Now update your both seeder as below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<?php namespace Database\Seeders; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; class UsersTableSeeder extends Seeder { /** * Run the database seeds. */ public function run(): void { DB::table('users')->insert([ [ 'name' => 'John Doe', 'password' => bcrypt('password123') ], [ 'name' => 'Jane Smith', 'password' => bcrypt('password456') ] ]); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<?php namespace Database\Seeders; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; class RolesTableSeeder extends Seeder { /** * Run the database seeds. */ public function run(): void { DB::table('roles')->insert([ [ 'name' => 'admin' ], [ 'name' => 'moderator' ], [ 'name' => 'subscriber' ] ]); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php namespace Database\Seeders; use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { /** * Seed the application's database. */ public function run(): void { $this->call([ UsersTableSeeder::class, RolesTableSeeder::class ]); } } |
Now run the below command
1 |
php artisan migrate:fresh --seed |
1 |
php artisan make:controller TestController |
Now update PostController like the below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?php namespace App\Http\Controllers; use App\Models\{ Role, User }; class TestController extends Controller { public function test() { // Create Records using Model $role_ids = [1, 2]; // Assuming id 1 is for Admin and id 2 for Moderator // $user->roles()->attach($role_ids); // Retrieve Records using Model. $user = User::find(1); dd($user->roles); // Get User Roles with pivot table } } |
For that simply go to web.php inside the Routes folder and update the file like below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\TestController; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider and all of them will | be assigned to the "web" middleware group. Make something great! | */ Route::get('/', [TestController::class, 'test']); |
Now simply run the below command.
1 |
php artisan serve |
Now you can simply check the output in the browser by hitting the above routes.
Thank you for reading this tutorial. We hope you found it helpful. If you have any questions or encounter any issues, please feel free to leave a comment below.
Additionally, if you’re looking to hire Laravel developers, you can visit the Hire Laravel Developer page. This platform provides a pool of experienced Laravel developers who can help you with your project requirements and ensure the successful implementation of your ideas.
Furthermore, if you’re interested in enhancing the functionality of Bagisto, you can check out the Extensions page on the official Bagisto website. This page showcases a wide range of extensions that can be integrated into your Bagisto e-commerce platform to add new features, improve user experience, and optimize your online store’s performance.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.