Belongs to many eloquent relationship in Laravel with Pivot table


Posted 6 years ago by Ryan Dhungel

Category: Eloquent Laravel

Viewed 7757 times

Estimated read time: 2 minutes

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>