For future viewers, starting with Laravel 5.2, there is a built-in function for calculating relationships without loading them without involving your model of resources or accessories -
In the context of the example in the approved answer, you will post in your controller:
$products = Product::withCount('orders')->get();
Now, when you iterate through $ products in your view, there is a orders_count column (or usually only << 22>) for each received product record, which you can simply display, like any other column value:
@foreach($products as $product) {{ $product->orders_count }} @endforeach
This method makes 2 queries to the database than the approved method for the same result, and the only involvement of the model is the correct establishment of your relationship. If you are using L5.2 + at this point, I would use this solution.
source share