elliotk
198
7
Laravel

Help Optimising Query

Posted 7 months ago by elliotk

Hello,

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) {
                                 $categories->with('media')->enabled()->first();
                            }])->get();

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

This returns all the correct data I need...

https://ek1.ams3.digitaloceanspaces.com/1.png

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

https://ek1.ams3.digitaloceanspaces.com/2.png

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.

Reply to

Use Markdown with GitHub-flavored code blocks.