Laravel has Many Through Relationship Example

In this post we learn Laravel has Many Through Relationship. has many through relationship in laravel 6, laravel 7 and laravel 8. In this example, I will create users, posts and countries tables. Each table is connected to each other. Now we will create has many through relationship with each other by using the laravel Eloquent Model.

Laravel has Many Through Relationship Example

Create Migrations:

countries table migration:

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

users table migration:

Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->unsignedBigInteger('country_id');
            $table->foreign('country_id')->references('id')->on('countries');
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });

posts table migration:

Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users');   
            $table->string("title");   
            $table->text("content");   
            $table->timestamps();
        });

Create Models:

Here, we will create Country model. we will also use hasManyThrough() for relationship of both model.

Read Also :  Laravel Carbon Subtract Minutes Example

Country Model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Country extends Model
{
    use HasFactory;
    
    public function posts()
    {
        return $this->hasManyThrough(
            Post::class,
            User::class,
            'country_id', // Foreign key on users table...
            'user_id', // Foreign key on posts table...
            'id', // Local key on countries table...
            'id' // Local key on users table...
        );
    }
}

Post Model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;

    public function user(){
        return $this->belongsTo(User::class,"user_id");
    }

    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
}

User Model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    use HasFactory;

    public function post()
    {
        return $this->hasOne(Post::class,"user_id");
    }

    public function posts()
    {
        return $this->hasMany(Post::class,"user_id");
    }

    public function roles()
    {
        return $this->belongsToMany(Role::class, 'role_user', 'user_id', 'role_id');
    }
}

Create Route

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostsController;
use App\Http\Controllers\ProvisionServer;
use App\Models\User;
use App\Models\Post;
use App\Models\Country;

Route::get("hasmanythrough", function(){
    $country = Country::find(1);	
    return $country->posts;
});

I hope you understand of laravel has Many Through relationship…

Read Also :  Laravel Collect Helper Methods Example