Belongs to many eloquent relationship in Laravel with Pivot table


Posted 3 months ago | by Ryan Dhungel | on Eloquent Laravel  | Viewed 407 times

Belongs to many relationship example in laravel

  • Create products and categories table along with migration
  • Populate the migration for products with title and price
  • Populate Categories with only title

Create pivot(lookup) table

  • Always make pivot table in alphabetical order
  • Always macke pivot table name singular
  • Always use underscore between two words(tables)

Run the following command to create a pivot table

php artisan make:migration create_category_product_table --create=category_product
  • Populate the migration with category_id and product_id
  • In both products and categories model use belongsToMany() relationship
$table->integer('product_id');
$table->integer('category_id');

Controller

  • Supply both products and categories to the view using compact function
  • Also use order by and paginate functions
public function show(Category $category)
{
$products = $category->products()->orderBy('created_at', 'desc')->paginate(5);
return view('category.show', compact('category', 'products'));
}

View

<div class="panel panel-default">
    <div class="panel-heading">{{ $category->title }}</div>
    <div class="panel-body">
        @if ($category->products->count())
            @foreach($category->products as $product)
                <h3>{{ $product->title }}</h3>
                <p>${{ number_format($product->price, 2) }}</p>
            @endforeach
        @endif  
    </div>
</div>


Specials


Build Laravel React CRUD/SPA APP in 2 hours
Build Laravel React CRUD/SPA APP in 2 hours

Build Laravel React CRUD/SPA APP in 2 hours

COUPON CODE: REACTCRUD with 90% off


Laravel with React JS - Build Twitter Like Real Ti...
Laravel with React JS - Build Twitter Like Real Time Web App

Laravel with React JS - Build Twitter Like Real Time Web App

COUPON CODE: LARAVELREACT with 90% off


Learn Laravel Building Multi User Blogging Platfor...
Learn Laravel Building Multi User Blogging Platform with SEO


React Redux Firebase CRUD App with Authentication
React Redux Firebase CRUD App with Authentication

React Redux Firebase CRUD App with Authentication

COUPON CODE: RRFTEN with 86% off


Become a Master of JavaScript from Scratch in 2018
Become a Master of JavaScript from Scratch in 2018

Become a Master of JavaScript from Scratch in 2018

COUPON CODE: JSMASTERSALE with 92% off


REACT - Up and Running with React ES6 and Open Sou...
REACT - Up and Running with React ES6 and Open Source API


Sublime Text for Rapid Web Development
Sublime Text for Rapid Web Development

Sublime Text for Rapid Web Development

COUPON CODE: LEARNSUBLIME with 90% off