Laravel Has Many Through Eloquent Relationship In Laravel 8

has many through relationship in laravel

In this article we will learn about has many through an eloquent relationship in Laravel 8. 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.

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.

You can also learn more about the eloquent relationship from the laravel official website from here.

To create has many through relationship in laravel, we will follow the below step.

  • Add column country in the user’s table
  • Create Post Model and Migration
  • Create Country Model and Migration
  • Retrieve Record

Step : 1 Add column country in the user’s table

Run the below command to add column country in the user’s table

php artisan make:migration add_country_to_users_table --table=users

The above command will create a migration file under database/migrations.

Add the below code in that file.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddCountryToUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->bigInteger('country_id')->unsigned()->index();
            $table->foreign('country_id')->references('id')->on('countries')->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            //
        });
    }
}

Step: 2 Create Post Model and Migration

Run the below code to create Post model and migration together

php artisan make:model post -m

Now go to database/migration and look for your Post migration file and the below code into it.

Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->string("name");
    $table->bigInteger('user_id')->unsigned();
    $table->timestamps();
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});

Step: 3 Create Country Model and Migration

Run the below code to create Country model and migration together

php artisan make:model country -m

Now go to database/migration and look for your Post migration file and the below code into it.

Schema::create('countries', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->timestamps();
});

Now go to app/Models and open the country.php file then add the below code into it.

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
        );
    }

Step: 4 Retrive Record

Now we will retrive record using has many through eloquent.

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

Read Also: Many to many relationship in laravel 8

Read Also: One to many relationship in laravel 8

Read Also: One to one relationship in laravel 8

I hope you like the article, Still confused feel free to comment.

5 1 vote
Article Rating

Do you want to hire us for your Project Work? Then Contact US.
Subscribe
Notify of
guest
1 Comment
oldest
newest most voted
Inline Feedbacks
View all comments
Sutar
Sutar
4 months ago

nice

1
0
Would love your thoughts, please comment.x
()
x