I've implemented this Laravel code in my controller for the detach function.
$input = Input::all();
$product= Products::findOrFail($input['product_id']);
$product->tags()->detach($input['tag_id']);
$product= Products::where('customer_id', Auth::user()->customers_id)->get();
return view('products.tagsdelete', [
'products' => $product,
]);
The current setup works well and successfully removes the tag relation from the pivot table. However, I'm looking to avoid page reloads when deleting a tag by using Ajax.
While I could implement a selection process for multiple tag deletions on user input, I prefer real-time deletion with Ajax for efficiency.
I've been trying to figure out how to incorporate detachment with Laravel and Ajax, but haven't found much guidance. Although I'm comfortable with JavaScript and jQuery, Ajax is still relatively new to me.
If anyone has any insights or can help me navigate through this, I would greatly appreciate it. Thanks for your time :)
@Wiriya Rungruang
Current Controller Code:
public function detach()
{
$input = Input::all();
$product= Products::findOrFail($input['product_id']);
$product->tags()->detach($input['tag_id']);
$product= Products::where('customer_id', Auth::user()->customers_id)->get();
}
My Button:
<button type="submit" class="delete-tag-btn" data-product_id="{{ $product->id }}" data-tag_id="{{ $tag->id }}"><i class="glyphicon glyphicon-trash"></i></button>
JavaScript at the Bottom of the Code:
<script>
$(".delete-tag-btn").on('click', function(){
var url = "{{ route('detach') }}"; // URL for deleteTag function
url += "product_id=" + $(this).data('product_id');
url += "&tag_id=" + $(this).data('tag_id');
// Updated URL: 'http://localhost/deletetag?product_id=2&tag_id=5'
// Send GET request with URL to server
$.get(url, function(response){
alert("success");
});
});
</script>