micky micky - 3 months ago 9
PHP Question

Reducing the similar like queries

I have these four similar like queries:

$products=Product::orderBy('views','desc')->with('category')->get(); //----1
$mostviews=Product::orderBy('views','desc')->limit(10)->get(); //----2
$show=Product::orderBy('views','desc')->with('category')
->with('user')
->with('productbrand.brand')
->first(); //----3

$shows=Product::orderBy('views','desc')->limit(20)
->with('category')
->with('user')
->with('productbrand.brand')
->get(); //----4


but for different purposes.



  1. to get all products with categories.

  2. to get 10 products

  3. to get one product with categories, users, and brand

  4. to get 20 products with categories, users, and brand



How can the queries be reduced?

Answer

You don't need to create all those variables. Just do this:

$products = Product::orderBy('views','desc')
                   ->with('category', 'user', 'productbrand.brand')
                   ->get();

After you got the data, use this variable. But I would also recommend you to not use take() method if you have product descriptions and/or specifications in DB. Because if you'll do this, it can easily take all memory. The thing is each take() will create new collection.

You can use $products without creating new collections or variables:

// Show:
{{ $products->first()->id }}

// Most views:
@foreach ($products as $product)
    @if ($loop->iteration > 10)
        @break
    @endif

    {{ $product->something }}
@endforeach

// Shows:
@foreach ($products as $product)
    @if ($loop->iteration > 20)
        @break
    @endif

    {{ $product->something }}
@endforeach