Has Many Through Relationship Laravel 9 Example

In this article, we will see that has many through relationship in laravel 9 example. hasManyThrough relationship is difficult to understand compared to other relationships. The has-many-through relationship provides a convenient way to access distant relations via an intermediate relation. You can use hasManyThrough relationship laravel 6, laravel 7 and laravel 8.

So, let's see laravel 9 has many through relationship, hasmanythrough in laravel 9 example, has many through pivot laravel 9, has many through laravel.

For example, a categories is connected with products, and products are connected with orders, then we can access all orders connected with specific categories. So, simply you can access or get data using intermediate model relation using hasManyThrough in laravel 9.

Now, we will create categories, products, and orders tables. categories table connected with products and products table connected with orders table like the below screenshot and we also create migration and model for all tables and retrieve data using the model.

has_many_through_relationship_laravel_9

 

Create Migration:

Categories Table

Schema::create('categories', function (Blueprint $table) {

    $table->increments('id');

    $table->string('name');

    $table->timestamps();

});

Products Table

Schema::create('products', function (Blueprint $table) {

    $table->increments('id');

    $table->integer('categories_id')->unsigned();

    $table->timestamps();

    $table->foreign('categories_id')->references('id')->on('categories')->onDelete('cascade');

});

Orders Table

Schema::create('orders', function (Blueprint $table) {

    $table->increments('id');

    $table->integer('product_id')->unsigned();

    $table->timestamps();

    $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');

});

 

 

Create Model:

Now, we will create a categories model and define relationships on the model.

Category Model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{    
    public function order()
    {
        return $this->hasManyThrough(Order::class, Product::class);
    }
}

The first argument passed to the hasManyThrough method is the name of the final model we wish to access, while the second argument is the name of the intermediate model.

Though the Order model table does not contain the category_id column, the hasManyThrough relation we can access $categories->orders like this.

Retrieve Records

Now, retrieve the record using the intermediate model through like below code example.

$category = Category::find(1);	
 
dd($category->order);

 


You might also like:

RECOMMENDED POSTS

FEATURE POSTS