10 months ago

Help Optimising Query

Posted 10 months ago by elliotk


I need some help optimising a query, and putting the correct syntax in to blade. At the moment, I am generating 12 SQL queries. I know 6 of them, come from blade, but the other 6, I am a bit lost on.

    public function index()
        $products = Product::with('media')->enabled()->promote()->inRandomOrder()->take(6)
                            ->with(['categories' => function ($categories) {

        //return response()->json($products);
        return view('home', compact('products'));

This returns all the correct data I need...


However, in blade, with the debugbar it gets awfully messy...


The first 6, I presume are to do with my above query - is that normal? Can it be improved? Of course I can cache it, but at the moment I am trying to optimise the queries themselves.

I know that the bottom 6 are due to the following line, but not sure how to correct that in my blade...

<a href="/{{ $product->categories()->first()->slug}}/{{ $product->slug }}">

I would have presumed that the first() wouldn't execute another query given the data is already passed, but I am fairly new to Laravel.

Any advice greatly received.

Please sign in or create an account to participate in this conversation.