Skip to content
  • Github
  • Facebook
  • twitter
  • About Us
  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Site Map

XpertPhp

Expertphp Is The Best Tutorial For Beginners

  • Home
  • Javascript
    • Jquery
    • React JS
    • Angularjs
    • Angular
    • Nodejs
  • Codeigniter
  • Laravel
  • Contact Us
  • About Us
  • Live Demos
Laravel many to many eloquent relationship tutorial example

Laravel many to many eloquent relationship tutorial example

Posted on December 2, 2019December 17, 2022 By XpertPhp 12 Comments on 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.

PHP
1
2
3
4
5
6
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Enter_Your_Database_Name(many_to_many_relation)
DB_USERNAME=Enter_Your_Database_Username(root)
DB_PASSWORD=Enter_Your_Database_Password(root)

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.

PHP
1
2
3
php artisan make:migration create_categories_table --create=categories
php artisan make:migration create_products_table --create=products
php artisan make:migration create_category_product_table --create=category_product

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

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCategoriesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('categories');
    }
}
?>

create_products_table.php

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->bigIncrements('id');
    $table->string('title');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
}
?>

create_category_product_table.php

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCategoryProductTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('category_product', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('category_id')->unsigned();
            $table->integer('product_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
            $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('category_product');
    }
}
?>
See also  Laravel One To Many Polymorphic Eloquent Relationship Tutorial Example

Run the below command. after the changes above file.

PHP
1
php artisan migrate

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.

PHP
1
2
3
php artisan make:model Category
php artisan make:model Product
php artisan make:model CategoryProduct

Category.php

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
    protected $fillable = [
        'name'
    ];
   /**
     * Get the products for the category.
     */
    public function products()
    {
return $this->belongsToMany(Product::class,'category_product');
    }
}
?>

Product.php

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
 
class Product extends Model
{
    /**
     * Get the category that owns the product.
     */
    public function categories()
    {
return $this->belongsToMany(Category::class,'category_product');
    }
}
 
?>

CategoryProduct.php

PHP
1
2
3
4
5
6
7
8
9
10
11
12
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class CategoryProduct extends Model
{
    //
}
 
?>

Route and Controller

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

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
    return view('welcome');
});
Route::get('product','productsController@index');
 
?>

Here below command help to create the product controller.

PHP
1
php artisan make:controller ProductsController

ProductsController.php

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
namespace App\Http\Controllers;
use App\Product;
use App\Category;
use Illuminate\Http\Request;
class ProductsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $product = Product::find(1);
        $category = Category::find(3);
dd($product);
dd($category);
    }
 
}
?>

Laravel, MySql Tags:laravel 6, Laravel 6 Eloquent, laravel 6 relationship, laravel 6 relationship eloquent

Post navigation

Previous Post: Laravel one to one eloquent relationship tutorial example
Next Post: node js routes in separate file using express

Latest Posts

  • Laravel 12 Ajax CRUD Example
  • Laravel 12 CRUD Example Tutorial
  • How to Create Dummy Data in Laravel 11
  • Laravel 11 Yajra Datatables Example
  • Laravel 11 Ajax CRUD Example
  • Laravel 11 CRUD Example Tutorial
  • Laravel 10 Ajax CRUD Example Tutorial
  • Laravel 10 CRUD Example Tutorial
  • How to disable button in React js
  • JavaScript Interview Questions and Answers

Tools

  • Compound Interest Calculator
  • Hex to RGB Color Converter
  • Pinterest Video Downloader
  • Birthday Calculator
  • Convert JSON to PHP Array Online
  • JavaScript Minifier
  • CSS Beautifier
  • CSS Minifier
  • JSON Beautifier
  • JSON Minifier

Categories

  • Ajax
  • Angular
  • Angularjs
  • Bootstrap
  • Codeigniter
  • Css
  • Htaccess
  • Interview
  • Javascript
  • Jquery
  • Laravel
  • MongoDB
  • MySql
  • Nodejs
  • Php
  • React JS
  • Shopify Api
  • Ubuntu

Tags

angular 10 tutorial angular 11 ci tutorial codeigniter 4 image upload Codeigniter 4 Tutorial codeigniter tutorial CodeIgniter tutorial for beginners codeigniter with mysql crud operation eloquent relationships file upload File Validation form validation Image Upload jQuery Ajax Form Handling jquery tutorial laravel 6 Laravel 6 Eloquent Laravel 6 Model laravel 6 relationship laravel 6 relationship eloquent Laravel 6 Routing laravel 7 Laravel 7 Eloquent laravel 7 routing laravel 7 tutorial Laravel 8 laravel 8 example laravel 8 tutorial laravel 9 example laravel 9 tutorial Laravel Framework laravel from scratch laravel social login learn jquery nodejs pagination payment gateway php with mysql react js example react js tutorial send mail validation wysiwyg editor wysiwyg html editor

Copyright © 2018 - 2025,

All Rights Reserved Powered by XpertPhp.com