Laravel Has Many Through Eloquent Relationship Example

Laravel 6 , Laravel , Laravel 7

Nicesnippets

7398

15-06-2020


Laravel Has Many Through Eloquent Relationship Example

Hi Guys,

In this tutorial, I Will explain how to create laravel Has many Through eloquent relationship.We will show Has many Through model relationship in laravel. For example, a country is connected with users and users with posts, then we can access all posts connected with a specific country.

you can understand how to create Has many through relationships with migration with a foreign key schema for Has many relationships, create records, attach records, get all records, where condition and everything related to has many through relationship.

In this example , we will create "user","post" and "country" table both table are connected with each other, i will create Has many Through relationship with each other by using laravel Eloquent Model, We will first create database migration, then model

Here the example of laravel Has many Through eloquent relationship.

Step:1 Create Migration


In this example, we will need two tables in our database employee and salary.I will start to create the model and migrations, then we will define the many to manmany relationship.To generate models and migrations, run below two commands in your terminal.

php artisan make:model User -m

php artisan make:model Post -m

php artisan make:model Country -m

Above command will generate two models in your app folder called Employee and Salary. You will also find two new migrations in your database/migrations folder.

Your newly created models and migration after add table field:

Path:database\migrations\2014_10_12_000000_create_users_table.php

<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

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

$table->id();

$table->string('name');

$table->string('email')->unique();

$table->timestamp('email_verified_at')->nullable();

$table->string('password');

$table->integer('country_id');

$table->rememberToken();

$table->timestamps();

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::dropIfExists('users');

}

}

Path:database\migrations\2014_10_12_000000_create_posts_table.php

<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

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

$table->id();

$table->string("name");

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

$table->timestamps();

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::dropIfExists('posts');

}

}

Path:database\migrations\2014_10_12_000000_create_countries_table.php

<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

class CreateCountriesTable extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

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

$table->id();

$table->string('name');

$table->timestamps();

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::dropIfExists('countries');

}

}

Now run the below command to create users, posts and country tables in your database:

php artisan migrate

Step:2 Create Model Relationship

Now in this step, we have Country ready, let’s define the many to Has many Through relationship in our models.

our app\Country.php model file and add a new function called posts() which will return a hasManyThrough relationship like below:

app\Country.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Country extends Model

{

Protected $fillable =[

'name',

];

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...

);

}

}

Step 3 : Retrieve Records

Now in this step retrieve records model

app\Http\Controllers\PostController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Country;

class PostController extends Controller

{

public function index()

{

$country = Country::find(1);

dd($country->posts);

}

}

it will help you....


Recommended Posts