Laravel Many to Many Eloquent Relationship Example

Today, We want to share with you Laravel Many to Many Eloquent Relationship Example.
In this post we will show you many to many relationship laravel 5.6, hear for laravel 5 save many to many relationship we will give you demo and example for implement.
In this post, we will learn about laravel 5 many to many sync with an example.

Laravel Many to Many Eloquent Relationship Demo

let’s start, I have to make database simple migration of main “employees”, “positions” and “position_employee” simple created table. I shall also put the main Laravel foreign key with employees and positions table. so let’s demo for Laravel Many to Many Eloquent Relationship make like as below:

READ :  Angular Dynamic Autocomplete Textbox

Create Migrations:

employees table migration:
[php]
Schema::create(’employees’, function (Blueprint $table) {
$table->increments(‘id’);
$table->string(‘name’);
$table->string(’email’)->unique();
$table->string(‘password’);
$table->rememberToken();
$table->timestamps();
});
[/php]
positions table migration:
[php]
Schema::create(‘positions’, function (Blueprint $table) {
$table->increments(‘id’);
$table->string(‘name’);
$table->timestamps();
});
[/php]
position_employee table migration:
[php]
Schema::create(‘position_employee’, function (Blueprint $table) {
$table->integer(’employee_id’)->unsigned();
$table->integer(‘position_id’)->unsigned();
$table->foreign(’employee_id’)->references(‘id’)->on(’employees’)
->onDelete(‘cascade’);
$table->foreign(‘position_id’)->references(‘id’)->on(‘positions’)
->onDelete(‘cascade’);
});
[/php]

Create Models:

User Model:
[php]
belongsToMany(Role::class, ‘position_employee’);
}
}
[/php]
Role Model:
[php]
belongsToMany(User::class, ‘position_employee’);
}
}
[/php]
UserRole Model:
[php]
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserRole extends Model
{

}
[/php]
Retrieve Records:
[php]
$employee = User::find(1);

dd($employee->positions);
[/php]
[php]
$role = Role::find(1);

dd($role->employees);
[/php]
Make Records:
[php]
$employee = User::find(2);

$roleIds = [1, 2];
$employee->positions()->attach($roleIds);
[/php]
[php]
$employee = User::find(3);

$roleIds = [1, 2];
$employee->positions()->sync($roleIds);
[/php]
[php]
$role = Role::find(1);

READ :  C# Continue keyword Tutorial with Examples

$employeeIds = [10, 11];
$role->employees()->attach($employeeIds);
[/php]
[php]
$role = Role::find(2);

$employeeIds = [10, 11];
$role->employees()->sync($employeeIds);
[/php]

jQuery 15 Powerful Tips and Tricks for Developers and Web Designer

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about laravel 5 many to many attach.
I would like to have feedback on my Infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Comment