Laravel hasManyThrough eloquent relationship tutorial example

Laravel hasManyThrough eloquent relationship tutorial example

In this tutorial, today we discuss about laravel hasManyThrough Eloquent relationship. Eloquent ORM means Object-relational Mapping and laravel provides a beautiful activerecord stucture. so we can easy to interact with application database. let’s start about hasManyThrough eloquent relationship.

Laravel hasManyThrough Eloquent relationship is woking with three tables of database. For example, The category is connected with products and products with orders, then we can access all orders connected with a specific category. categories have many products and products have many orders.

here, see below database stucture.


– id

– name


– id

– category_id

– title


– 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 categories, products and orders table migration.

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




Run the below command. after the changes above file.

Create Model

Here below command help through we will create the Category, Product and Order model. we will also use “hasManyThrough()” or relationship of both model.




Route and Controller

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

Here below command help to create the product controller.


Please follow and like us: