I want to store product_id and subcategory_id in the pivot table. Can you help me.
- Product has many categories
- the subcategory has many products
In the category model
public function products()
{
return $this->belongsToMany(Product::class,'product_SubCategory','product_id','subcategory_id');
}
in product Model
public function subcategory()
{
return $this->belongsToMany(SubCategory::class,'product_SubCategory','subcategory_id','product_id' );
}
in Create Product View,
<form action="{{route('product.store')}}" method="POST" enctype="multipart/form-data">
@csrf
<div class="item form-group">
<label class="col-form-label col-md-3 col-sm-3 label-align" for="first-name">Product Name
<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 ">
<input type="text" id="first-name" required="required" class="form-control"
name="pro_name">
</div>
</div>
<div class="item form-group">
<label class="col-form-label col-md-3 col-sm-3 label-align" for="first-name"> Sub Category
<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 ">
<div class="form-check">
@foreach ($subcategory as $item)
<div class="form-check">
<input class="form-check-input" type="checkbox" name="subcategory[]"
value="{{$item->id}}" id="defaultCheck1">{{$item->name}}
</div>
@endforeach
</div>
</div>
</div>
<button type="submit" class="btn btn-success btn-lg btn-block">Add Product</button>
</form>
in dd($request)
+request: Symfony\Component\HttpFoundation\ParameterBag {#44 ▼
#parameters: array:8 [▼
"_token" => "3YxgjIZn5nTPzd09NtjNfR3ViooXYIY7OomdGKiR"
"pro_name" => null
"category" => "3"
"subcategory" => array:2 [▼
0 => "1"
1 => "2"
]
]
}
Store in Controller,
$product = new Product();
$product->pro_name = $request->pro_name;
$product->save();
$subcategory= new subcategory();
$subcategory->subcategory = $request->subcategory;
$product->subcategory()->save($subcategory);
return redirect()->route('product.index');