Search code examples
phplaraveleloquentquery-optimizationlaravel-query-builder

Laravel how can optimize multi queries that separated by only statuses


Now I am getting all items, active items, inactive items and their counts using 3 queries.

This is current my function to get them.

public function getItems()
{
    $items = $this->model->with('category')->latest()->get();
    $count['all'] = $items->count();
    $all = view('components.item', compact('items'))->render();

    $items = $this->model->with('category')->latest()->whereStatus(1)->get();
    $count['active'] = $items->count();
    $active = view('components.item', compact('items'))->render();

    $items = $this->model->with('category')->latest()->whereStatus(0)->get();
    $count['inactive'] = $items->count();
    $active = view('components.item', compact('items'))->render();

    return response()->json([
       'all'=>$all
       'active'=>$active,
       'inactive'=>$inactive,
       'count'=>$count
    ]);

}

How can I optimize those quires to one?

Thanks


Solution

  • Just retrieve only once

    $items = $this->model->with('category')->latest()->get();
    

    and then filter with collection where method

    //active
    $activeItems = $items->where('status', 1);
    $activeCount = $activeItems->count();
    
    //inactive
    $inactiveItems = $items->where('status', 0);
    $inactiveCount = $inactiveItems->count();