This is the fourth blog post of Laravel relationship Model tutorial series. In this tutorial, we are going to learn how to implement hasManyThrough relationship within our Laravel application

Prerequisites

  • Laravel
  • To Continue with this tutorial, you should have installed Laravel in your pc. If you are still not installed Laravel in your machine you can configure it from here.

    Setting up the Project

    First you need to create a new laravel project by running below command in your terminal
    1
    composer create-project laravel/hasManyThrough-example

    Then navigate to your project directory by using below command in your terminal

    1
    cd hasManyThrough-example

    In here we will use hasManyThrough() relation.

    Create Migration

    Now we have to create migration of "users", "posts" and "countries" tables.
  • Users table migration
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('email')->unique();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
    $table->foreign('country_id')->references('id')->on('countries')
    ->onDelete('cascade')
    });
  • Posts table migration
  • 1
    2
    3
    4
    5
    6
    7
    8
    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
  • 1
    2
    3
    4
    5
    Schema::create('countries', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->timestamps();
    });

    Create Models

    Now we need to create Country table model. we will also use "hasManyThrough()" for relationship of both model.
  • Country Model:
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    <?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...
    );
    }
    }

    Retrieve Records

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

    In this tutorial, we learn how to implement hasManyThrough relationship within Laravel. If you have any issue regarding this tutorial, mention your issue in comment section or reach me through my E-mail.