Recent Topics

List products by category in one page



  • Hi,

    I have created package where I want list categories and filter products by category name.

    I don't know how exactly filter products by one view and in bagisto here is list products by category page e.g. example.com/category-name

    I try to use this example, but can't get it working, because I don't know where I get class "Products" and function AllProducts.

    Can someone guide me in the right direction of how I could get this to work correctly? This is what I'm trying to do: https://codepen.io/mrsingleton/pen/aYVBvV

    My code in products view:

    $categories = [];
    
    foreach (app('Webkul\Category\Repositories\CategoryRepository')->getVisibleCategoryTree(core()->getCurrentChannel()->root_category_id) as $category) {
    
    array_push($categories, $category);
    
     }
                
     ?>
    
        @if (count($categories))
    
            <div class="list-container" style="text-align:center;margin-top: 50px;">
               <ul class="list-group">
    
                 @foreach ($categories as $key => $category)
                     
                      <li> {{ $category->name }} </li>
                 
                 @endforeach
                 
               </ul> 
            </div>
    
        @endif 
    


  • Hi @PyramidHead,

    The first thing is this, you need to fetch the categories first, for e.g. in controller you can fetch all by this,

    $categories = Category::all();

    Now, if you check the Category model, this model is already related to products,

    foreach ($categories as $category) {
        $product = $category->product;
        ...
    }
    


  • @devansh-webkul

    Thanks for the response. Can you still tell how I can make this code working:

    Because category id's is not stored in the products table

    public function allProducts(Request $request){
            if(!empty($request->category)){
                $data = products::whereIn('category_id',$request->category)->paginate(12);
                return response()->json($data);
            }
            $data = products::paginate(12);
            return response()->json($data);
        }
    


  • Hi @PyramidHead,

    Please check this,

    public function allProducts(Request $request){
        if (! empty($request->category)) {
            $data = Category::find('id', $request->category)->products->paginate(12);
            return response()->json($data);
        }
    
        $data = Product::paginate(12);
        return response()->json($data);
    }
    

Log in to reply