Database relationships are an important part of web application development because they allow you to easily model and access data from connected tables. The “Has Many Through” connection in Laravel 10, a strong PHP framework, provides a straightforward way to get data from distant related tables through intermediate tables.
In Laravel, the “Has Many Through” relationship is a type of Eloquent relationship that allows you to define a many-to-many relationship with another model through a third intermediate model. This relationship is useful when you have complex relationships between models that can’t be directly related to each other.
In this tutorial, we will walk you through the process of constructing a “Has Many Through” connection in Laravel 10’s Eloquent ORM, which will allow you to manage and retrieve related data from your database more effectively.
Read More: Laravel 10 Many-to-Many Eloquent Relationship Tutorial
For this tutorial we will consider a people table, brokers table and homes table. This means a person will contact a broker, then broker will provide home list.
Person -> Broker -> Home
Let’s get started.
Laravel Installation
Open terminal and run this command to create a laravel project.
composer create-project laravel/laravel myblog
It will create a project folder with name myblog inside your local system.
To start the development server of laravel –
php artisan serve
URL: http://127.0.0.1:8000
Assuming laravel already installed inside your system.
Create Database & Connect
To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.
CREATE DATABASE laravel_app;
To connect database with application, Open .env file from application root. Search for DB_ and update your details.
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=laravel_app DB_USERNAME=root DB_PASSWORD=root
Create Migrations & Database Tables
To get idea about “has many through” relationship you need few migration files,
- People migration for people table to store people data
- Broker migration for brokers table to store brokers
- Home Migration for homes table to store homes data
Open project into terminal and run these artisan commands.
php artisan make:migration create_people_table
php artisan make:migration create_brokers_table
php artisan make:migration create_homes_table
It will create two migration files xxx_create_people_table.php, xxx_create_brokers_table.php, and xxx_create_homes_table.php inside location /database/migrations.
Read More: Laravel 10 One to Many Eloquent Relationship Tutorial
Open xxx_create_people_table.php and write this complete code into it.
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up(): void { Schema::create('people', function (Blueprint $table) { $table->id(); $table->string("name", 120); $table->string("email", 120)->unique(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down(): void { Schema::dropIfExists('people'); } };
Open xxx_create_brokers_table.php and write this code into it.
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up(): void { Schema::create('brokers', function (Blueprint $table) { $table->id(); $table->string("name", 120); $table->string("email", 120)->unique(); $table->foreignId('person_id')->constrained('people'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down(): void { Schema::dropIfExists('brokers'); } };
Open xxx_create_homes_table.php and write this complete code into it.
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up(): void { Schema::create('homes', function (Blueprint $table) { $table->id(); $table->string("title", 155); $table->text("location"); $table->foreignId('broker_id')->constrained('brokers'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down(): void { Schema::dropIfExists('homes'); } };
Run Migrations
Next, you need to migrate migrations.
php artisan migrate
This command will create tables inside database.
Setup Model with Has-Many-Through Relationship
Back to terminal and run these artisan commands,
php artisan make:model Person
php artisan make:model Broker
php artisan make:model Home
These commands will create three files Person.php, Broker.php and Home.php inside /app/Models folder.
Open Person.php and write this complete code into it.
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Relations\HasManyThrough; use Illuminate\Database\Eloquent\Model; use App\Models\Home; use App\Models\Broker; class Person extends Model { use HasFactory; public function homeList(): HasManyThrough { return $this->hasManyThrough(Home::class, Broker::class); } }
$this->hasManyThrough(Home::class, Broker::class); This is establishing Has Many Through Relationship.
The first argument passed to the hasManyThrough
method is the name of the final model we wish to access, while the second argument is the name of the intermediate model.
Read More: Laravel 10 One to One Eloquent Relationship Tutorial
Rest for all models like for Broker.php and Home.php code will be same as default code.
Usage
$homes = Person::find($person_id)->homeList;
How To Use Relation in Laravel Controller?
Let’s test with a dummy application controller class.
Open any controller say DataController.php file from /app/Http/Controllers folder.
Here, you can see a method in which we used model method as a property.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Person; class DataController extends Controller { // To get home detail of a person public function getHome($person_id) { return Person::find($person_id)->homeList; } }
Explanation,
- Person::find($person_id)->homeList; It returns the list of homes by person_id through broker. It is showing has many through relationship.
Add Route
Open web.php from /routes folder and add this route into it.
//... use App\Http\Controllers\DataController; Route::get('home-list/{id}', [DataController::class, 'getHome']); //...
Application Testing
Run this command into project terminal to start development server,
php artisan serve
URL
Get Homes by person id: http://127.0.0.1:8000/home-list/1
That’s it.
We hope this article helped you to learn about Laravel 10 Eloquent Has Many Through Relationship Tutorial in a very detailed way.
Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.
If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.