Laravel Many to Many Eloquent Relationship Example

Laravel 6 , Laravel , Laravel 7

Nicesnippets

109

13-06-2020


Hi Guys,

In this tutorial, I Will explain you how to create laravel Many to Many eloquent relationship. We will create Many to many relationship in laravel. We will learn you how we can create migration with foreign key schema, retrieve records, insert new records, update records etc. I will show you laravel Many to Many relationship example.

We will create "user" ,"role_user" and "role" table.both table are connected with each other, I will create Many to many relationship with each other by using laravel Eloquent Model, We will first create database migration, then model, retrieve records and then how to create records too. Many to Many Relationship use "belongsToMany()" for relation.

Here, I will give you full example for laravel Many to Many eloquent relationship as bellow.

Step:1 Create Migration

In this example, we will need two tables in our database user ,role_user and role. I will start to create the model and migrations, then we will define the Many to many to Many relationship.To generate models and migrations, run below two commands in your terminal.

php artisan make:model User -m

php artisan make:model RoleUser -m

php artisan make:model Role -m

Above command will generate two models in your app folder called user and role. You will also find two new migrations in your database/migrations folder.

Your newly created models and migration after add table field:

Path:database\migrations\2014_10_12_000000_create_user_table.php

<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

class CreateUserTable extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

Schema::create('user', 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('user');

}

}

Path:database\migrations\2014_10_12_000000_create_role_table.php

<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

class CreateRoleTable extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

Schema::create('role', function (Blueprint $table) {

$table->id();

$table->string('name');

$table->timestamps();

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::dropIfExists('role');

}

}

Path:database\migrations\2014_10_12_000000_create_role_users_table.php

<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

class CreateRoleUsersTable extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

Schema::create('role_users', function (Blueprint $table) {

$table->id();

$table->string('name');

$table->integer('user_id');

$table->integer('role_id');

$table->timestamps();

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::dropIfExists('role_users');

}

}

Now run the below command to create user and role tables in your database:

php artisan migrate

Step:2 Create Model Relationship

Now in this step, we have user ,role_user and role tables ready, let’s define the Many to manMany relationship in our models.

our app\user.php model file and add a new function called roles() which will return a many to Many relationship like below:

app\user.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class user extends Model

{

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

*/

public function roles()

{

return $this->belongsToMany(Role::class, 'role_users');

}

}

you can see, in the roles() method we are defining a Many to Many relationship on role model.

Now we will defining Inverse Many To Many Relationship in Laravel.As we have defined the many to Many relationship on Brand model which return the related records of role model, we can define the inverse relationship on the role model.Open your app/role.php model file and add a new method called users() in it which will return the related brand of a role.

app\role.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model

{

/**

* The attributes that should be hidden for arrays.

*

* @var array

*/

Protected $fillable=[

'name'

];

/**

* The attributes that should be hidden for arrays.

*

* @var array

*/

public function users()

{

return $this->belongsToMany(User::class, 'role_users');

}

}

you can see, in the users() method we are defining a Many to Many relationship on role model.

app\RoleUser.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class RoleUser extends Model

{

/**

* The attributes that should be hidden for arrays.

*

* @var array

*/

public $table = 'role_user';

/**

* The attributes that should be hidden for arrays.

*

* @var array

*/

protected $fillable = [

'user_id','role_id'

];

}

Step 3 : Insert Records

Let’s in this step add data to user and role from controller:

app\Http\Controllers\user.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\User;

use App\Role;

class userController extends Controller

{

public function createRecored()

{

//create recored in user table

$user = User::find(2);

$roleIds = [1, 2];

$user->roles()->attach($roleIds);

$user = User::find(3);

$roleIds = [1, 2];

$user->roles()->sync($roleIds);

//create recored in role table

$role = Role::find(1);

$userIds = [10, 11];

$role->users()->attach($userIds);

$role = Role::find(2);

$userIds = [10, 11];

$role->users()->sync($userIds);

}

}

Step 4 : Retrieve Records

Now in this step retrieve records model

app\Http\Controllers\user.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\User;

use App\Role;

class userController extends Controller

{

public function retrieveRecords()

{

//Retrieve recoed in user table

$user = User::find(1);

dd($user->roles);

//Retrieve recoed in role table

$role = Role::find(1);

dd($role->users);

}

}

it will help you....


Recommended Posts