In this tutorial you will learn about the Laravel Has Many Through Eloquent Relationship Example and its application with practical example.
In this Laravel HasManyThrough relationship example tutorial, I’ll show you how to create hasmany through relationship in eloquent models. In this tutorial you will also learn to implement and use Laravel Has Many Through Eloquent Relationship.
Laravel Eloquent HasMany Through Relationship Example
In this Laravel Has Many Through Eloquent Relationship tutorial we will implement an example for the Laravel Has Many Through Eloquent Relationship. We will generate migration files of “users”, “posts” and “countries” table and then add a foreign key with users and posts table as following:
In users migration file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
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:
1 2 3 4 5 6 7 8 9 |
Schema::create('countries', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->timestamps(); }); |
In laravel, the “has-many-through” relationship provides a shortcut for accessing distant relations via an intermediate model relation. For example, a Country
model might have many Post
models through an intermediate User
model. In this example, we can easily get all blog posts of a given country. I’ll show you how to define HasMany Through relationship:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?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:
1 2 3 |
$country = Country::find(1); dd($country->posts); |