Is new Products(); supposed to be new Product();
Oct 8, 2024
6
Level 4
Modal Showing Incorrect Category Name When Adding Products in Laravel
I'm working on a Laravel application where I have a modal to add products to categories. However, the modal always displays the name of the last category instead of the one associated with the plus sign I clicked. Here's the code
HTML THE FIRST IMPLEMENTATION
<a href="#" id="addProductButton" class="add" data-category-id="{{ $category->id }}" data-category-name="{{ $category->category_name }}" data-target=".AddProductsModal" data-toggle="modal"><i class="bi bi-plus-lg text-white"></i></a>
<div class="modal fade AddProductsModal" id="AddProductsModal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Add Products to {{$category->category_name ?? 'No Category'}} </h5>
<button type="button" class="close" data-dismiss="modal"><span>×</span>
</button>
</div>
<div class="modal-body">
<form method="POST" id="addProductForm" action="{{ route('addextraproductToCategory', $category->id) }}">
@csrf
<textarea name="addProductToCategory" id="addProductToCategory" cols="2" rows="1" class="form-control bg-transparent" title="Add Your Product Here" required></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</div>
</form>
</div>
</div>
</div>
SECOND IMPLEMENTATION
<a href="#" id="addProductButton" class="add" data-category-id="{{ $category->id }}" data-target=".AddProductsModal" data-toggle="modal"><i class="bi bi-plus-lg text-white"></i></a>
HERE IS THE JS for the first IMPLEMENTATION
<script>
$(document).ready(function() {
$('#addProductButton').on('click', function() {
var categoryId = $(this).data('category-id');
var categoryName = $(this).data('category-name');
// Update modal title and form action
$('#AddProductsModal .modal-title').text('Add Products to ' + categoryName);
$('#addProductForm').attr('action', '/addextraproductToCategory/' + categoryId);
// Clear the textarea for new input
$('#addProductToCategory').val('');
});
});
</script>
the Controller works fine
// add extra product to category
public function addextraproductToCategory(Request $request, $id) {
// Validate input
$request->validate([
'addProductToCategory' => 'required|string|max:255',
]);
// Find the category
$category = Category::find($id);
if (!$category) {
return redirect()->back()->with('error', 'Category not found.');
}
// Create a new product
$product = new Products();
$product->product_name = $request->input('addProductToCategory');
$product->category_id = $category->id;
$product->save();
return redirect()->back()->with('success', 'Product added to category successfully.');
}
Please or to participate in this conversation.