Laravel Has Many Through Eloquent Relationship Example
Laravel 24-Dec-2020

Laravel Has Many Through Eloquent Relationship Example

Laravel HasManyThrough relationship example. In this tutorial, you will learn how to create hasmany through relationship in eloquent models and as well as how to use it.

Laravel Eloquent HasMany Through Relationship Example

Create migration of “users”, “posts” and “countries” table and add a foreign key with users and posts table as follow:

In users migration file:

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

 

In posts migration file:

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

In countries migration file:

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

The “has-many-through” relationship provides a convenient shortcut for accessing distant relations via an intermediate relation. For example, a Country model might have many Post models through an intermediate User model. In this example, you could easily gather all blog posts for a given country. Let’s look at how to define HasMany Through relationship:

<?php
 
namespace App;
 
use Illuminate\Database\Eloquent\Model;
 
class Country extends Model
{
    /**
     * Get all of the posts for the country.
     */
    public function posts()
    {
        return $this->hasManyThrough('App\Post', 'App\User');
    }
}

To fetch data using this relationship as follow:

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