Skip to content
Advertisement

Laravel: Count number of rows in a relationship

I have the following relationship:

  • A venue has many offers
  • A offer has many orders

I have the following Eloquent model to represent this:

class Venue {
    public function orders()
    {
        return $this->hasManyThrough(Order::class, Offer::class);
    }
}

I want to determine the total number of orders for venues with location_id = 5 using Laravel’s Eloquent model.

The only way I managed to do this is as follows:

$venues = Venue::where('location_id', 5)->with('orders')->get();

$numberOfOrders = 0;
foreach($venues as $venue) {
    $numberOfOrders += $venue->orders->count();
}
dump($numberOfOrders); // Output a single number (e.g. 512)

However, this is obviously not very efficient as I am calculating the count using PHP instead of SQL.

How can I do this using Eloquent model alone.

Advertisement

Answer

You can use Eloquent. As of Laravel 5.3 there is withCount().

In your case you will have

$venues = Venue::where('location_id', 5)->with('orders')->withCount('orders')->get();

Then access it this way

foreach ($venues as $venue) {
    echo $venue->orders_count;
}

Can find reference here: https://laravel.com/docs/5.3/eloquent-relationships#querying-relations

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement