How to use Many through relationship in Laravel?

Many through relationship is very interesting relationship between tables in Laravel. Lets suppose we have cities table and in each city there are multiple stores and each store has multiple products. Now if we want to get products of each city through stores then we can implement that with incredible amount of simplicity.  Lets start with migrations.

This is schema in cities migration.

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

And this is schema in store migration.

Schema::create('stores', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('address');
            $table->bigInteger('city_id')->unsigned();
            $table->foreign('city_id')->references('id')->on('cities');
            $table->timestamps();
});

And this is the schema in products migration.

Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->float('price');
            $table->text('description');
            $table->bigInteger('store_id')->unsigned();
            $table->foreign('store_id')->references('id')->on('stores');
            $table->timestamps();
});

Now this is the code we need to add in our City Model and everything will work great.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class City extends Model {
	public function products() {
		return $this->hasManyThrough(Product::class, Store::class, 'city_id', 'store_id');
	}
}

If we want to get products in any city we can just type and retrieve results like this.

$city->products;

I hope now you understand everything about many through relationship. If you have any questions please leave a comment.