Laravel eloquent relationship is a very important feature which connects one or more tables in a chain. This is the substitute of joins in laravel.
Laravel provides these following relationships –
- One To One
- One To Many
- Many to Many
- Has One Through
- Has Many Through
Eloquent relationships are defined as methods on your Eloquent model classes. Inside this article we will see the concept of laravel 9 Has Many through Eloquent relationship.
This article will give you the detailed concept of about implementation of Has Many through relationship in laravel.
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
Learn More –
- How To Install Laravel 9 on Ubuntu Step by Step Tutorial
- Laravel 9 Call MySQL Stored Procedure Tutorial
- Laravel 9 Google reCaptcha v3 Tutorial with Validation
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
We need few migration files –
- People migration to store people data
- Broker migration to store brokers
- Home Migration 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 2022_04_03_162204_create_people_table.php, 2022_04_03_162246_create_brokers_table.php, and 2022_04_03_162253_create_homes_table.php at location /database/migrations.
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() { 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() { 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() { 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() { 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() { 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() { Schema::dropIfExists('homes'); } };
Run Migrations
Next, we need to migrate migrations.
$ php artisan migrate
This command will create tables inside database.
Create Model
Next, we need to create three models. 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 & 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\Model; use App\Models\Home; use App\Models\Broker; class Person extends Model { use HasFactory; public function homeList() { return $this->hasManyThrough(Home::class, Broker::class); } }
$this->hasManyThrough(Home::class, Broker::class); This line is implementing the relationship i.e Has Many Through
Rest for all models like for Broker.php and Home.php code will be same as default code.
Sample Data Insertion
Open mysql and run these queries to insert dummy data into people, brokers and homes table.
Data for People Table
-- -- Dumping data for table `people` -- INSERT INTO `people` (`id`, `name`, `email`, `created_at`, `updated_at`) VALUES (1, 'Sanjay Kumar', 'sanjay@gmail.com', NULL, NULL), (2, 'Ashish Kumar', 'ashish@gmail.com', NULL, NULL);
Data for Brokers Table
-- -- Dumping data for table `brokers` -- INSERT INTO `brokers` (`id`, `name`, `email`, `person_id`, `created_at`, `updated_at`) VALUES (1, 'Broker 1', 'broker1@gmail.com', 1, NULL, NULL), (2, 'Broker 2', 'broker2@gmail.com', 2, NULL, NULL);
Data for Homes Table
-- -- Dumping data for table `homes` -- INSERT INTO `homes` (`id`, `title`, `location`, `broker_id`, `created_at`, `updated_at`) VALUES (1, 'Home 1', 'Location 1, Street 1, Sample', 2, NULL, NULL), (2, 'Home 2', 'Location 2, Street 2, Sample', 1, NULL, NULL), (3, 'Home 3', 'Location 3, Street 3, Sample', 2, NULL, NULL), (4, 'Home 4', 'Location 4, Street 4, Sample', 2, NULL, NULL), (5, 'Home 5', 'Location 5, Street 5, Sample', 1, NULL, NULL);
Controller Usage
Open any controller say DataController.php file from /app/Http/Controllers folder.
Here, we have created 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; } }
- Person::find($person_id)->homeList; It returns the list of homes by person_id through broker. It is showing has many through relationship.
Create 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
We hope this article helped you to learn Laravel 9 Has Many Through Eloquent 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.