Laravel Many to Many Eloquent Relationship Tutorial
https://www.itsolutionstuff.com/post/laravel-many-to-many-eloquent-relationship-tutorialexample.html
Laravel Many to Many Eloquent Relationship Tutorial
By Hardik Savani October 10, 2020 Category : PHP Laravel
Powered ByPauseUnmuteLoaded: 1.84%Fullscreen
Many to many relationship is a little bit complicated than one to one and one to many relationships. An example of such a relationship is a user with may have multiple roles, where the role are also connected with multiple users. many to many relationship in laravel 6, laravel 7, laravel 8 and laravel 9.
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 database table structure on 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:
roles table migration:
role_user table migration:
Create Models:
Here, we will create User, Role and UserRole table model. we will also use "belongsToMany()" for relationship of both model.
User Model:
Role Model:
UserRole Model:
Retrieve Records:
Create Records:
Read Also: Laravel One to One Eloquent Relationship Tutorial
I hope you understand of many to many relationship...
Last updated