How To Get Total Result Count in Laravel Eloquent

PHPPHP FrameworksDatabasesLaravel
Part of the Series: A Practical Introduction to Laravel Eloquent ORM

Eloquent is an object relational mapper (ORM) that is included by default within the Laravel framework. In this project-based series, you’ll learn how to make database queries and how to work with relationships in Laravel Eloquent. To follow along with the examples demonstrated throughout the series, you’ll improve a demo application with new models and relationships. Visit the series introduction page for detailed instructions on how to download and set up the project.

When working with database query results, it is often useful to obtain only the total number of rows in a result set, instead of pulling the full dataset content with a regular query. Eloquent offers a few different aggregate methods that return a scalar number instead of an Eloquent object, including count(), max(), and sum(), among others. These are all made available through the inherent query builder that is built into every Eloquent model.

In this part of the series, you’ll update the main application view to show the total number of links in each list.

Open the file resources/views/index.php in your code editor:


Locate the paragraph styled with the subtitle class, which contains the foreach loop that renders the application menu:

<p class="subtitle">
     @foreach ($lists as $list)<a href="{{ route('link-list', $list->slug) }}" title="{{ $list->title }}" class="tag is-info is-light">{{ $list->title }}</a> @endforeach

To obtain the total number of links in each list, you can access the query builder from within the $list->links() relationship method defined on the LinkList class, and call the count() method that is available through the query builder:

{{ $list->links()->count() }}

Update the code inside the foreach loop to include the count() method call, which will display the number of links in a list. Make sure to place it inside the <a> tag and right after the list title. You can wrap this information inside a parenthesis for more readability in the rendered HTML output.

This is how the code should look like once you are finished:

 <p class="subtitle">
      @foreach ($lists as $list)<a href="{{ route('link-list', $list->slug) }}" title="{{ $list->title }}" class="tag is-info is-light">{{ $list->title }} ({{ $list->links()->count() }})</a> @endforeach

Save the file when you’re finished. Then, reload the main application page on your browser:


You’ll obtain a page like the following, showing the total number of links included in each list, on the top menu:

Updated application showing number of links in each link on the top menu

In the next part of this series, you’ll learn how to limit the number of results in a query, and how to paginate results in Laravel Eloquent.

Creative Commons License