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

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *