Laravel many to many eloquent relationship tutorial example – onlinecode
In this post we will give you information about Laravel many to many eloquent relationship tutorial example – onlinecode. Hear we will give you detail about Laravel many to many eloquent relationship tutorial example – onlinecodeAnd how to use it also give you demo for it if it is necessary.
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.
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 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 use IlluminateSupportFacadesSchema; use IlluminateDatabaseSchemaBlueprint; use IlluminateDatabaseMigrationsMigration; 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 use IlluminateSupportFacadesSchema; use IlluminateDatabaseSchemaBlueprint; use IlluminateDatabaseMigrationsMigration; 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 use IlluminateSupportFacadesSchema; use IlluminateDatabaseSchemaBlueprint; use IlluminateDatabaseMigrationsMigration; 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'); } } ?>
Run the below command. after the changes above file.
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 artisan make:model Category php artisan make:model Product php artisan make:model CategoryProduct
Category.php
<?php namespace App; use IlluminateDatabaseEloquentModel; 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 namespace App; use IlluminateDatabaseEloquentModel; class Product extends Model { /** * Get the category that owns the product. */ public function categories() { return $this->belongsToMany(Category::class,'category_product'); } } ?>
CategoryProduct.php
<?php namespace App; use IlluminateDatabaseEloquentModel; class CategoryProduct extends Model { // } ?>
Route and Controller
We have to need put below code route in routes/web.
<?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 artisan make:controller ProductsController
ProductsController.php
<?php namespace AppHttpControllers; use AppProduct; use AppCategory; use IlluminateHttpRequest; class ProductsController extends Controller { /** * Display a listing of the resource. * * @return IlluminateHttpResponse */ public function index() { $product = Product::find(1); $category = Category::find(3); dd($product); dd($category); } } ?>
Hope this code and post will helped you for implement Laravel many to many eloquent relationship tutorial example – onlinecode. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs