Answer the question
In order to leave comments, you need to log in
Why is the product category not being deleted?
Hello
In the admin panel on the product editing page, using ajax, I delete the category that is linked to this product.
app/Http/Controllers/Admin/ProductsController.php
public function deleteProductCategory(Request $request){
if($request->ajax()){
$product_id = (int)$request->input('product_id');
$category_id = (int)$request->input('category_id');
$objCategoriesRelationship = new CategoriesRelationship();
$objCategoriesRelationship->where('object_id', $product_id)->where('category_id', $category_id)->delete();
echo 'Success';
}
}
routes/web.php
Route::delete('/products/productcategory/delete', 'Admin\[email protected]')->name('admin.products.productcategory.delete');
resources/views/admin/products/products/edit.blade.php
$('.delete-product-category').on('click', function(e){
e.preventDefault();
if(confirm('Вы действительно хотите удалить категорию у товара?')){
let product_id = $(this).attr('productId');
let category_id = $(this).attr('catId');
$.ajax({
type: "DELETE",
url: "{!! route('admin.products.productcategory.delete') !!}",
data: {
_token:"{{csrf_token()}}",
_token:"{{csrf_token()}}",
category_id: category_id,
object_id: product_id,
},
success: function(){
alert("Категория товара удалена.");
// location.reload();
}
});
} else {
alertify.error("Действие отменено пользователем.");
}
});
Answer the question
In order to leave comments, you need to log in
depending on the relationship
$product = Product::find($product_id);
// hasMany
$product->category->delete();
// manyToMany
$product->categories()
->find($category_id)
->delete();
// Просто удалить категорию
Category::find($id)->delete();
// Удалить категорию У товара (открепить)
$product->categories()
->detach($category_id);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question