Laravel many to many eloquent relationship tutorial example

Laravel many to many eloquent relationship tutorial example

In this tutorial, today we discuss about laravel many to many 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 many to many eloquent relationship.

Laravel many to many relationship is a complicated better than one to one and one to many relationships. Many-to-many relationship are returns the result of the belongsToMany data. For example, Many-to-many relationship such as one product can belong to multiple categories, and one category can have multiple products.

here, see below database stucture.

Categories

– id

– name

Products

– id

– title

category_product

– id

– category_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 category_product 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_category_product_table file.

create_categories_table.php

create_products_table.php

create_category_product_table.php

Run the below command. after the changes above file.

Create Model

Here below command help through we will create the Category, Product and CategoryProduct model. we will also use “belongsToMany()” for a both model.

Category.php

Product.php

CategoryProduct.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: