How To Define Has Many Through Relationships With Laravel

admin_img Posted By Bajarangi soft , Posted On 08-09-2020

The "has-many-through" relationship provides a convenient shortcut for accessing distant relations via an intermediate relation

How To Define Has Many Through Relationships With Laravel

Has Many Through Relationships

Lets start.
How to define Has Many Through Eloquent Relationship

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 the tables required to define this relationship:

 

1.Create laravel project and connect to database in .env file.

composer create-project laravel/laravel World --prefer-dist


2.Create Model and Migrate it.
To implement  Has One Through Relationships in Laravel, we need models: Country ,Post and Users.

Now we need to create  Country,Post and Users models in fresh project so for that run below commands in comand prompt.
php artisan make:model Country -m

php artisan make:model Post -m

php artisan make:model User -m

 

3.After Created Models we need to Implement code in Model and migration files as below

Migration files
2020_09_07_111458_create_countries_table.php

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCountriesTable extends Migration
{
    public function up()
    {
        Schema::create('countries', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('countries');
    }
}
 

2020_09_07_111619_create_posts_table.php

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->bigInteger('user_id ')->unsigned()->index();
            $table->foreign('user_id')->references('id')->on('users')
                ->onDelete('cascade');
            $table->timestamps();
        });
    }

  
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

2020_09_07_000000_create_users_table.php
 
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->bigInteger('country_id')->unsigned()->index();
            $table->foreign('country_id')->references('id')->on('countries')
                ->onDelete('cascade');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('users');
    }
}


migrate the schema files using the following command
php artisan migrate

Models

Country .php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Country extends Model
{
    protected $fillable = [
        'name'
    ];
    public function posts()
    {
        return $this->hasManyThrough(
            'App\Post',
            'App\User',
            '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.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $fillable = [
        'user_id','title '
    ];
}

User.php

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;


class User extends Authenticatable
{
    use Notifiable;
    protected $fillable = [
        'name', 'country_id',
    ];

}

4.Create route and controller to access data.

Route in Web.php

Route::get('hasmany','WorldController@hasmany');


Create WorldController.php using below command in command prompt

php artisan make:controller WordController


Implement code in WorldController.php as below
 
<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use App\Country;
use App\Post;

class WordController extends Controller
{
    //
    public function hasmany()
    {
       $country = Country::find(1);dd($country->posts);
       return 'done';

    }
}

Related Post