Laravel 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

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of 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 from a starting stage. As well as demo example.

Leave a Reply

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