last day (16 days later) » 

4:57 PM
2
A: How can I update pivot table on laravel?

Gabriel CarusoTry to use the sync() function Product::find($product_id)->categories()->sync($array_of_categories_id)

 
@Gabriel Caruso, Your answer seems correct. It seems that it also does not use loops. I will make sure again. Btw, I want to ask. How do you think my code to add data. I use a loop to add category. Does it need not use loop?
@Amit Gupta, Yes, seems the answer correct. But I will make sure again. Btw, How do you think my code to add data? Is that true? I use loop to add it
 
Loop is not always the best way. Image that your product has 1.000 categories, 1.000 loops? No! Database (like MySQL) alows you to batch insert, and the sync() function uses this!
 
@Gabriel Caruso, I am confused if not using a loop. How can I get the category? Maybe you can update your answer. So besides exist code for update category, there is also exist code to add category
@Amit Gupta, I am confused if not using a loop. How can I get the category?
 
@TrendingNews to access your categories by a product, just use the many to many relationship like $product->categories()->get(), and here you can loop. But, to add and update your relationship, just use the sync() method
 
@Gabriel Caruso, Great. I use this : Product::find($product_id)->categories()->sync($param['categ‌​ory']); to add and update category, it works. Thanks a lot
 
4:57 PM
@TrendingNews Glad I could help. If you can, mark this answer as the correct one, I'd appreciate that :)
 
@Gabriel Caruso, Okay. I will give you answer. But I want ask one last question. This is about delete category on the table pivot. I try like this : Product::find($product_id)->categories()->where('product_id'‌​, $product_id)->delete();. But it does not works. There exist error : Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails. How can I delete category correctly?
 
@TrendingNews This is a security reason. Use the detach() method from the documentation, and should work. Ex: Product::find($product_id)->categories()->where('product_id'‌​‌​, $product_id)->detach(); to remove all relations and then Product::find($product_id)->categories()->where('product_id'‌​‌​, $product_id)->delete();
 
@Gabriel Caruso, There exist error. This code : ->where('product_id'‌​‌​, $product_id). That's what caused the error. There seems to be a misplaced or wrong field call
 
@TrendingNews Wow, not seen that coming. Please, chat me and I’ll try to help you!
@TrendingNews I need the full code to see what’s going on
 
public function destroy($id)
{
$result = Product::find($id)->categories()->where('product_id'‌​‌​, $id)->delete();
return $result;
}
parameter $id is product id
I want to ask
This : $result = Product::find($id)->categories()->where('product_id'‌​‌​, $id)->delete();
product_id? Does it mean product_id from the pivot table (products_categories?
 

  last day (16 days later) »