The Has Many Through connection is a little difficult to grasp, but it provides a quick way to get data from another mode relationship. If, for example, a country is linked to users and users to posts, we can view all posts associated with that country. In Laravel 6, Laravel 7, Laravel 8, and Laravel 9, there are several via relationships.
So, in this lesson, you'll learn how to establish has many through relationships using migration and a foreign key schema for one-to-many connections, as well as how to create records, attach records, get all records, use where conditions, and more.
I'll make tables for "users," "posts," and "countries" in this example. Each table is linked to the others. Using Laravel Eloquent Model, we will now construct many to many relationships with each other. We'll start with database migration, then move on to models, retrieving records, and finally creating records.

"hasManyThrough()" will be used for relation in Has Many Through Relationship.

1. Create Migrations

Now we must migrate the tables "users," "posts," and "countries." With the users and posts tables, we'll also add a foreign key. So, let's make something like this:

users table migration
Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('email')->unique();
    $table->string('password');
    $table->integer('country_id')->unsigned();
    $table->rememberToken();
    $table->timestamps();
    $table->foreign('country_id')->references('id')->on('countries')
                ->onDelete('cascade');
});
 
posts table migration
Schema::create('posts', function (Blueprint $table) {
    $table->increments('id');
    $table->string("name");
    $table->integer('user_id')->unsigned();
    $table->timestamps();
    $table->foreign('user_id')->references('id')->on('users')
                ->onDelete('cascade');
});
countries table migration
Schema::create('countries', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->timestamps();
});

2. Create Models

We'll make a country model here. For the relationship between the two models, we'll utilise "hasManyThrough()"

Country Model
<?php
 namespace App;
 use Illuminate\Database\Eloquent\Model;
 class Country extends Model
 {
    public function posts()
    {
        return $this->hasManyThrough(
            Post::class,
            User::class,
            '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...
        );
    }
 }
?>

3. Retrieve Records

$country = Country::find(1);    
dd($country->posts);

I hope you will like the content and it will help you to learn Laravel Has Many Through Eloquent Relationship
If you like this content, do share.


Recommended Posts

View All

Laravel 8 Install Bootstrap Example Tutorial


laravel ui, laravel ui bootstrap 4, bootstrap 4, laravel 8 install bootstrap 4, install bootstrap 4 in laravel 8, how to use bootstrap in laravel 8

How to Send SMS using Twilio in Laravel


Twilio shares cloud communications trends, customer tales, and advice for using Twilio's APIs to build scalable voice and SMS applications.

Laravel whereHas and orWhereHas Query Example


laravel whereHas and orWhereHas query example, wherehas and orWhereHas query in laravel, how to use wherehas in laravel

Laravel 9 ConsoleTvs Charts Tutorial Example


consoletvs/charts laravel 9 ,consoletvs charts laravel 9 ,laravel 9 chart consoletvs ,consoletvs/charts laravel 9 tutorial ,laravel charts,laravel ch...

Laravel Multiple Where Condition Example


Laravel multiple where condition, Laravel multiple where not working, Laravel multiple where same column, Laravel 8 Eloquent multiple where condition...