Skip to content
Advertisement

In laravel, how do I generate an array of counts?

For example, I have several orders, and each order is related to a zone(there are 10 zones). I want the number of orders for each zone so 10 rows. Something like this:

Select count(*) as aggregate from orders group by zone_id

I tried using count and groupby methods but it generates an integer.

Order::groupBy('zone_id')->count();

Any suggestions?

Advertisement

Answer

Try using withCount – laravel docs

You will need to add a relationship in your zone model, add the following

class Zone extends Model
{
     public function orders()
     {
         return $this->hasMany(Order::class);
     }
}

The eloquent query – the “orders” is the name of the method in your model (above)

$zones = Zone::withCount('orders')->get();

Then in your blade file

@foreach($zones as $zone)
    {{ $zone->name }} --- {{ $zone->orders_count }}
@endfoeach
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement