To display products by categories using Laravel, you first need to set up a database table to store the products and another table to store the categories. Let’s assume you already have these tables created with the appropriate fields.
In your Laravel project, you will have a Product model and a Category model. These models will represent the tables in the database. It’s recommended to use Laravel’s Eloquent ORM for easier database querying.
First, define the relationships between the Product and Category models. In the Category model, add the following method:
public function products()
{
return $this->hasMany(Product::class);
}
This establishes the “one-to-many” relationship between categories and products.
In the Product model, add the following method:
public function category()
{
return $this->belongsTo(Category::class);
}
This creates the inverse relationship between products and categories, allowing you to access the category of a product.
Now, in your controller, you can retrieve the products by categories using the following code:
public function index()
{
$categories = Category::with('products')->get();
return view('products.index', compact('categories'));
}
The “with” method eager loads the products associated with each category, reducing the number of database queries.
In your view file, you can loop through the categories and display the products. Here’s an example:
<ul>
@foreach ($categories as $category)
<li>{{ $category->name }}</li>
<ul>
@foreach ($category->products as $product)
<li>{{ $product->name }} - {{ $product->price }}</li>
@endforeach
</ul>
@endforeach
</ul>
This code outputs a nested unordered list where each category is displayed as a list item, and the associated products are listed underneath.
Make sure to adjust the variable names and HTML structure according to the structure of your database and design requirements.
- How to call a function from another component in react
- How to create multiple tables in sqlite android studio
- How to change namespace in c# visual studio
- How to compare two objects in c# using linq
- How to break foreach loop in flutter
- How to count visitors on website in laravel 8
- How to display console output in tkinter
- How to display different navbar component for different reactjs pages