Laravel hasOneThrough Eloquent Relationship Tutorial Example

Laravel hasOneThrough Eloquent Relationship Tutorial Example

In this tutorial, today we discuss laravel many to many Eloquent relationships. Eloquent ORM means Object-relational Mapping and laravel provides a beautiful ActiveRecord structure. so we can easy to interact with the application database. let’s start about hasOneThrough eloquent relationship.

The “HasOneThrough” relationship links models through a single intermediate relation. For example, if each category has one product, and each product is associated with one product order record, then the category model may access the order through the product.

here, see below database structure.

Products

– id

– category_id

– title

Categories

– id

– name

Orders

– id

– product_id

Setting Database Configuration

After complete installation of laravel. we have to database configuration. now we will open the .env file and change the database name, username, password in the .env file. See below changes in a .env file.

Create Table using migration

Now, We need to create a migration. so we will below command using create the products, categories and orders table migration.

After complete migration. we need below changes in the database/migrations/create_products_table, database/migrations/create_categories_table and database/migrations/create_orders_table file.

create_products_table.php

create_categories_table.php

create_orders_table.php

Run the below command. after the changes above file.

Create Model

Here below command help through we will create the Product, Category and Order model. we will also use “hasOneThrough()” method relations based on the foreign key between any two table.

Product.php

Category.php

Order.php

Route and Controller

We have to need put below code route in routes/web.

Here below command help to create the product controller.

ProductsController.php

Please follow and like us: