Laravel – Get All Products from Parent Category and its Subcategories
To get all products from a parent category and its subcategories in Laravel, you can use recursive queries or recursive relationships. In this example, we will use recursive relationships.
Database Structure
Assuming you have the following database structure:
categories - id - name - parent_id products - id - name - category_id
Models and Relationships
First, let’s define the necessary models and their relationships:
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasMany; class Category extends Model { public function products(): HasMany { return $this->hasMany(Product::class); } public function subcategories(): HasMany { return $this->hasMany(self::class, 'parent_id', 'id'); } } class Product extends Model { public function category() { return $this->belongsTo(Category::class); } }
Controller Method
Next, let’s define a controller method to fetch all products from a parent category and its subcategories:
use App\Models\Category; public function getAllProductsFromParentCategory() { $parentCategory = Category::find($parentId); $products = $parentCategory->products()->with('subcategoryProducts')->get(); // 'subcategoryProducts' is a relationship defined in the Category model for retrieving products from subcategories // Get all products including the parent category and its subcategories $allProducts = $products->mergeRecursive($parentCategory->subcategoryProducts); return view('products.index', compact('allProducts')); }
View
Finally, let’s update the view to display the products:
<h2>All Products</h2> <ul> @foreach ($allProducts as $product) <li>{{ $product->name }} - {{ $product->category->name }}</li> @endforeach </ul>
In the above example, we first fetch the parent category using Category::find($parentId)
. We then retrieve all products from the parent category and its subcategories using the products()
relationship with with('subcategoryProducts')
to include subcategory products. We merge the parent category’s products with the subcategory products using mergeRecursive()
. Finally, we pass the $allProducts
variable to the view and iterate over it to display the product names and their categories.
Note: Replace $parentId
with the actual ID of the parent category you want to retrieve products from.
With the above code, you should be able to retrieve all products from a parent category and its subcategories in Laravel.
- Find Location By Latitude And Longitude Google Maps Javascript
- Html table javascript add column dynamically?
- Session Has Not Been Configured For This Application Or Request
- Get Address From Latitude And Longitude Google Map Api Using Javascript
- How To Fetch Products By Category In Laravel E-Commerce Filter By Category