Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kaiserkais's avatar

Query builder with resource and sum

HI guys im trying to sort data based on sum with query builder my resource is like this

public function toArray($request)
    {
        return [
            // 'id'=>$this->id,
            'name'=>$this->name,
            'url'=>$this->url,
            'image_path'=>$this->image_path,
            // 'orders' => $this->orders,
            'weekly'=>$this->orders->take(7)->sum('orders_number'), // this is sort i want to 
            'daily'=>$this->orders->take(1)->sum('orders_number'),
            'halfweek'=>$this->orders->take(15)->sum('orders_number'),
        ];
    }

i want to be able to sort it based on weekly values asc or desc and i cant figure it out how to do it.

0 likes
2 replies
drewdan's avatar
'weekly' => $this-orders->whereBetween('created_at', [Date::now()->subDays(7), Date::now])->count();

assuming that $this->orders is a collection, you can use collection helpers to search in it to narrow the data and then count the amount of results

Please or to participate in this conversation.