Laravel has many eloquent relationship; Through this tutorial, i am going to show you what is has many relationship and how to use has many relationship in laravel apps.
The “has-many-through” relationship provides a convenient way to access distant relations via an intermediate relation
Laravel 11 Has Many Through Eloquent Relationship Example Tutorial
- Create Migrations
- Create Models
- Retrieve Records
- Create Records
Create Migrations
To create migration of “users”, “posts” and “countries” table. we will also add foreign key with users and posts table. so let’s create like as below:
First of create users table migration; so use the following code:
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');
});
Then create posts table migration; so use the following code:
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');
});
Then create countries table migration; so use the following code:
Schema::create('countries', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Create Models
To create Country table model. And use “hasManyThrough()” for relationship of both model.
Create Country Model; and add the following code into it:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Country extends Model
{
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...
);
}
}
Retrieve Records
Use the following queries to get or fetch records from database using relationship in laravel apps:
$country = Country::find(1); dd($country->posts);