Laravel Has Many Through Eloquent Relationship Tutorial

By Hardik Savani | July 7, 2018 | Category : PHP Laravel

Has 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 and laravel 8.

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:

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











posts table migration:

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








countries table migration:

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





Create Models:

Here, we will create Country model. we will also use "hasManyThrough()" for relationship of both model.

Country Model:


namespace App;

use Illuminate\Database\Eloquent\Model;

class Country extends Model


public function posts()


return $this->hasManyThrough(



'country_id', // Foreign key on users table...

'user_id', // Foreign key on posts table...

'id', // Local key on countries table...

'id' // Local key on users table...




Retrieve Records:

$country = Country::find(1);


I hope you understand of one to one relationship...

*** Click On it and Read in Details of RelationShip types:

Hardik Savani
My name is Hardik Savani. I'm a full-stack developer, entrepreneur and owner of Aatman Infotech. 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, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.
Follow Me: Github Twitter
***Do you want me hire for your Project Work? Then Contact US.

We are Recommending you: