Laravel one to many eloquent relationship tutorial example

Laravel one to many eloquent relationship tutorial example

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

Laravel one to many relationships is based work on the one table row connected with multiple tables rows. For example, the category has multiple products.

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 and products table migration.

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

create_categories_table.php

create_products_table.php

Run the below command. after the changes above file.

Create Model

Here below command help through we will create the Category and Product model. we will also use “hasMany()” for a category model and “belongsTo()” for a product model.

Category.php

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