Laravel Has Many Through Eloquent Relationship Tutorial
https://www.itsolutionstuff.com/post/laravel-has-many-through-eloquent-relationship-tutorialexample.html
Last updated
https://www.itsolutionstuff.com/post/laravel-has-many-through-eloquent-relationship-tutorialexample.html
Last updated
By Hardik Savani July 7, 2018 Category : PHP LaravelPlayUnmute40%Loaded: 1.15%FullscreenHas Many Through relationship is a bit complicated to understand a provide shortcut way to access data of another mode relation. For example, a country is connected with users and users with posts, then we can access all posts connected with a specific country. has many through relationship in laravel 6, laravel 7, laravel 8 and laravel 9.
So in this tutorial you can understand how to create has many through relationships with migration with a foreign key schema for one to many relationships, create records, attach records, get all records, where condition and everything related to has many through relationship.
In this example, I will create "users", "posts" and "countries" tables. each table is connected with each other. now we will create many to many relationship with each other by using the laravel Eloquent Model. We will first create database migration, then models, retrieve records and then how to create records too. So you can also see database table structure on below screen.
Has Many Through Relationship will use "hasManyThrough()" for relation.
Create Migrations:
Now we have to create migration of "users", "posts" and "countries" table. we will also add foreign key with users and posts table. so let's create like as below:
users table migration:
posts table migration:
countries table migration:
Create Models:
Here, we will create Country model. we will also use "hasManyThrough()" for relationship of both model.
Country Model:
Retrieve Records:
Read Also: Laravel One to One Eloquent Relationship Tutorial
I hope you understand of one to one relationship...
*** Click On it and Read in Details of RelationShip types: