Saturday, October 11, 2025
HomeLanguagesLaravel 10 HasMany Through Eloquent Relationship Example

Laravel 10 HasMany Through Eloquent Relationship Example

Laravel 10 HasManyThrough relationship example; In this tutorial, you will learn how to create hasmany through relationship in eloquent models & 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);

Recommended Laravel Tutorials

Recommended:-Laravel Try Catch

RELATED ARTICLES

Most Popular

Dominic
32352 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6720 POSTS0 COMMENTS
Nicole Veronica
11885 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11941 POSTS0 COMMENTS
Shaida Kate Naidoo
6840 POSTS0 COMMENTS
Ted Musemwa
7104 POSTS0 COMMENTS
Thapelo Manthata
6795 POSTS0 COMMENTS
Umr Jansen
6794 POSTS0 COMMENTS