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:

JavaScript

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:

JavaScript

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

JavaScript

Then access it this way

JavaScript

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