Laravel 8 Has One Through Eloquent Relationship Tutorial

Share this Article
Reading Time: 7 minutes
27 Views

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 –

Eloquent relationships are defined as methods on your Eloquent model classes. Inside this article we will see the concept of laravel 8 Has One through Eloquent relationship.

This article will give you the detailed concept of about implementation of Has One 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 to take a home

Person -> Broker -> Home

Let’s get started.


Installation of Laravel 8 Application

Laravel Installation can be done in two ways.

  • Laravel Installer
  • By using composer

Laravel Installer

To install Laravel via Laravel installer, we need to install it’s installer first. We need to make use of composer for that.

$ composer global require laravel/installer

This command will install laravel installer at system. This installation is at global scope, so you type command from any directory at terminal. To verify type the given command –

$ laravel

This command will open a command palette of Laravel Installer.

To create ad install laravel project in system,

$ laravel new blog

With the name of blog a laravel project will be created at your specified path.

By using composer

Alternatively, we can also install Laravel by Composer command create-project. If your system doesn’t has Composer Installed, Click here to Install Composer ? Here is the complete command to create a laravel project-

$ composer create-project --prefer-dist laravel/laravel blog

After following these steps we can install a Laravel 8 application into system. To start the development server of Laravel –

$ php artisan serve

This command outputs –

Starting Laravel development server: http://127.0.0.1:8000

Assuming laravel 8 already installed at 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 2021_05_03_162204_create_people_table.php, 2021_05_03_162246_create_brokers_table.php, and 2021_05_03_162253_create_homes_table.php at location /database/migrations.

Open 2021_05_03_162204_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;

class CreatePeopleTable 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 2021_05_03_162246_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;

class CreateBrokersTable 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->unsignedBigInteger('person_id');
            $table->timestamps();
            $table->foreign('person_id')->references('id')->on('people');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('brokers');
    }
}

Open 2021_05_03_162253_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;

class CreateHomesTable 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->unsignedBigInteger('broker_id');
            $table->timestamps();
            $table->foreign('broker_id')->references('id')->on('brokers');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('homes');
    }
}

Run Migrations

Next, we need to create tables inside database.

$ 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 at /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 homeInformation()
    {
        return $this->hasOneThrough(Home::class, Broker::class);
    }
}

$this->hasOneThrough(Home::class, Broker::class); This line is implementing the relationship i.e Has One 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);

Calling Method at Controller

Open any controller say SiteController.php file, we have created one method in which we used model method as a property.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Person;

class SiteController extends Controller
{
    // To get home detail of a person
    public function getHome()
    {
        return Person::find(1)->homeInformation;
    }
}

Person::find(1)->homeInformation; It will return the home information of person by it’s ID.


Create Routes

Open web.php from /routes folder and add this route into it.

# Add this to header
use App\Http\Controllers\SiteController;

Route::get('home-information', [SiteController::class, 'getHome']);

Application Testing

Open project to terminal and type the command to start development server

$ php artisan serve

Get Home Information by Person ID – http://127.0.0.1:8000/home-information

We hope this article helped you to learn about Laravel 8 Has One Through Eloquent Relationship Tutorial in a very detailed way.

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.

Find More on Laravel 8 Articles here

Leave a Comment