Ad

Counting Data Before Sending To View In Laravel

- 1 answer

I have two tables, products and product_images, now I want to show product which has at least one image.

In controller I have a simple function in ProductController to fetch all the products:

public function products(){
    $allProducts = $this->product->paginate(15);
    return view('frontend.pages.products',compact('allProducts'));
}

But, I want to send the products which has at least one image of each product.

What should I do to achieve that?

Edit:

I have created relationship between tables, now how can I get my desired answer?

I have written this in the Controller:

$allProducts = $this->product->whereHas('product_images', function ($query){
        $query->where();
    })->get();
Ad

Answer

Assuming table schema

product

    -id
    -name

product_image

    -id
    -product_id
    -url //any columns you needed


$product_ids = DB::table('product')
                  ->join('product_image','product_image.product_id','=','product.id')
                  ->select('product.id','roduct.name')
                  ->groupBy('product.id')
                  ->get();

$product_count = count($product_ids);
Ad
source: stackoverflow.com
Ad