wd's avatar
Level 1

efficient query method LARAVEL

Hi, I am currently building an e-commerce site and I would like to display a product preview by category through queries in my Controller. But after realization I find myself with too many requests that make the page change slow. I would like to know if there is not a more efficient method. here is my code :

 public function index()
    {
      

        //for phone
        $phones = Product::with(['poster'])->where('category_id', 1)->get();

        //for bag
        $bags = Product::with(['poster'])->where('category_id', 2)->get();

        $produits = Product::with(['poster'])->where('category_id', 3)->get();

        //for games
        $games = Product::with(['poster'])->where('category_id', 4)->get();


        return view('guest.pages.index', compact(
            'phones',
            'bags',
            'games'
        ));
    }
0 likes
1 reply
martinbean's avatar

@wd Well, yeah. Every time you call get you’re issuing a database query, so you’re executing at least four in that controller action alone.

I don’t really understand what you’re trying to do; you just seem to be fetching all products for four different categories, so just do that in one query:

$products = Product::with('poster')->whereIn('category', [1, 2, 3, 4])->get();

Please or to participate in this conversation.