To display products by categories using Laravel and JavaScript, you can follow these steps:
- Create a route in your Laravel application to handle the category view.
- Create a controller method that retrieves the products filtered by category.
- Create a view file to display the products and their respective categories.
- Use JavaScript to dynamically update the product list based on the selected category.
Let’s go through each step with examples:
// Step 1: Create a route in your Laravel application
Route::get('/products/{category}', 'ProductController@showByCategory');
// Step 2: Create a controller method
public function showByCategory($category)
{
$products = Product::where('category', $category)->get();
return view('products.index', compact('products'));
}
// Step 3: Create a view file (products/index.blade.php)
<div id="category-filter">
<select id="category-select">
<option value="all">All Categories</option>
<option value="category1">Category 1</option>
<option value="category2">Category 2</option>
<option value="category3">Category 3</option>
</select>
</div>
<div id="product-list">
<ul>
@foreach($products as $product)
<li>{{ $product->name }} - {{ $product->category }}</li>
@endforeach
</ul>
</div>
// Step 4: Use JavaScript to update the product list
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$('#category-select').change(function() {
var category = $(this).val();
if (category === 'all') {
$('#product-list li').show();
} else {
$('#product-list li').each(function() {
if ($(this).text().indexOf(category) !== -1) {
$(this).show();
} else {
$(this).hide();
}
});
}
});
});
</script>
In the above example, when the user selects a category from the dropdown, the JavaScript code hides/shows the products based on the selected category. The “category” parameter is passed to the controller method, which retrieves the matching products from the database and renders them in the view file.
Same cateogry post
- Don’t Allow Special Characters In Textbox Javascript
- How To Add Multiple Markers On Google Maps Javascript Dynamically
- Asp.Net Mvc Redirect To Action In Another Controller
- How Do I Change Marker Cluster Options & How Do I Customize The Cluster Icon Using Google Maps Api With Markerclusterer
- How To Call Rest Api From Excel Vba And Parse Json Example