Belongs to many eloquent relationship in Laravel with Pivot table


Posted 7 months ago by Ryan Dhungel

Category: Eloquent Laravel

Viewed 785 times

Estimated read time: 2 minutes

Course of the day!

React Redux Firebase CRUD App with Authentication

React Redux Firebase CRUD App with Authentication

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>