Laravel: many to many relationship - luannguyenQV/laravel-framework-demo-full-blog GitHub Wiki

As you can see in Laravel document: https://laravel.com/docs/5.3/eloquent-relationships#many-to-many, we have enough document for Many to Many relationship. And, in my project, I apply for: Product and Category[Nested Category], Post and Tag. But, the most difficult thing spend my time is how to edit the Products, with many checkbox for Category. I try to find how to apply HTMLCollective for this case, but no result.

Here is my Solution.

Product vs Category

Product:

class Product extends Model

{

`public function categories() {`

    `return $this->belongsToMany('App\Category', 'products_categories'); //product_id category_id`

`}`

}

Category: class Category extends Node {

/** * Table name. * * @var string */ protected $table = 'categories';

public function products() { return $this->belongsToMany('App\Product', 'products_categories'); } } _** That is nested category using Baum Nested Category _

ProductController > Edit

public function edit($id) { $product = Product::find($id); $curCategory = $product->categories; return view('backend.products.edit')->with([ 'product' => $product, 'categories' => $this->categories, 'curCategory' => $curCategory, ]);
}

Product > edit.blade.php

@foreach($categories as $node)

@if ($curCategory->contains('id', $node->id)) {!! Form::checkbox($node->id, $node->id, true) !!} @else {!! Form::checkbox($node->id, $node->id, null) !!} @endif {!! Form::label($node->id, $node->name, ['class' => 'control-label']) !!}
@endforeach
⚠️ **GitHub.com Fallback** ⚠️