Laravel 10 Many to Many Eloquent Relationship Tutorial
Hi Developer,
Here, I will show you many to many relationship laravel 10. It's a simple example of laravel 10 many to many relationship example. you can understand a concept of laravel 10 belongstomany tutorial. I explained simply step by step laravel 10 many to many sync.
So in this tutorial, you can understand how to create many-to-many relationships with migration with a foreign key schema for one to many relationships, use sync with a pivot table, create records, attach records, get all records, delete, update, where condition and everything related to many to many relationship.
In this example, i will create "users", "roles" and "role_user" tables. each table is connected with each other. now we will create many to many relationships with each other by using the laravel Eloquent Model. We will first create database migration, then model, retrieve records and then how to create records too. So you can also see the database table structure on the below screen.
Many to Many Relationship will use "belongsToMany()" for relation.
Create Migrations:
Now we have to create migration of "users", "roles" and "role_user" table. we will also add foreign key with users and roles table. so let's create like as below:
users table migration:
<?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('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(): void
{
Schema::dropIfExists('users');
}
};
roles table migration:
<?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');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down(): void
{
Schema::dropIfExists('roles');
}
};
role_user table migration:
<?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');
}
};
Create Models:
Here, we will create User, Role and UserRole table model. we will also use "belongsToMany()" for relationship of both model.
User Model:
<?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;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* The roles that belong to the user.
*/
public function roles(): BelongsToMany
{
return $this->belongsToMany(Role::class, 'role_user');
}
}
Role Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
class Role extends Model
{
use HasFactory;
/**
* The users that belong to the role.
*/
public function users(): BelongsToMany
{
return $this->belongsToMany(User::class, 'role_user');
}
}
UserRole Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class UserRole extends Model
{
use HasFactory;
}
Retrieve Records:
$user = User::find(1);
dd($user->roles);
$role = Role::find(1);
dd($role->users);
Create Records:
$user = User::find(2);
$roleIds = [1, 2];
$user->roles()->attach($roleIds);
$user = User::find(3);
$roleIds = [1, 2];
$user->roles()->sync($roleIds);
$role = Role::find(1);
$userIds = [10, 11];
$role->users()->attach($userIds);
$role = Role::find(2);
$userIds = [10, 11];
$role->users()->sync($userIds);
I hope you understand of many to many relationship...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel 10 One to One Relationship Example
- How to Generate QR Code in Laravel 10?
- How to Create Custom Error Page in Laravel 10?
- Laravel 10 Ajax CRUD Tutorial Example
- How to Generate Barcode in Laravel 10?
- Laravel 10 Get Current Logged in User Data Example
- Laravel 10 Resize Image Before Upload Example
- Laravel 10 Scout Full Text Search Tutorial
- How to Get Last Executed Query in Laravel 10?
- Laravel 10 Ajax Image Upload Example
- Laravel 10 Mail | Laravel 10 Send Mail Tutorial
- Laravel 10 Auth with Livewire Jetstream Example
- Laravel 10 Import Export Excel and CSV File Tutorial
- Laravel 10 CRUD Application Example Tutorial