Skip to content

All topics  /  Laravel

Laravel 9 Has Many Through Eloquent Relationship Tutorial

Laravel ·

Teams applying “Laravel 9 Has Many Through Eloquent Relationship Tutorial” in a production project can use read the supporting guide to record implementation, review and debugging time, then compare that effort with tests and shipped functionality instead of treating activity as performance by itself.

Before copying the example into a live application, confirm version-specific behaviour with the official Laravel website and test it against the project’s actual database and runtime.

Hi friends,

Today, I explain has many through relationship examples in laravel 9. I will give you simply example of laravel 9 has many through pivot table. In this tutorial you can understand how to hasonethrough and hasmanythrough relationship. you will learn how to create hasmany through relationship in eloquent models and as well as how to use it. We will show has many through model relationship in laravel 9.

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 the database table structure on the below screen.

So let's start following example

Step 1: Download Laravel


Let us begin the tutorial by installing a new laravel application. if you have already created the project, then skip following step.

composer create-project laravel/laravel example-app

Step 2: Add 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:

database/Migrations/create_users_table.php

<?php

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

  
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->foreignId('country_id')->constrained('countries');
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
};
php artisan make:migration create_posts_table

database/Migrations/create_posts_table.php

<?php

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

  
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string("name");
            $table->foreignId('user_id')->constrained('users');
            $table->timestamps();
        });
    }

  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
};
php artisan make:migration create_countries_table

database/Migrations/create_countries_table.php

<?php

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

  
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('countries', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });
    }

  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('countries');
    }
};

Step 3: Add Models

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

php artisan make:model Country 

app/Models/Country.php

<?php

  
namespace App\Models;

  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

  
class Country extends Model
{
    use HasFactory;
    /**
     * Write code on Method
     *
     * @return response()
     */
    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: Add Controllrt

php artisan make:controller UserController
<?php

  
namespace App\Http\Controllers;

  
use Illuminate\Http\Request;
use App\Models\Country;

  
class UserController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $country = Country::find(1);    

   
        dd($country->posts);
    }
}

I hope it will help you...