How To Get Total Result Count in Laravel Eloquent

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:

resources/views/index.php

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
</p>
...

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
 </p>

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

http://localhost:8000

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.

This tutorial is part of an ongoing weekly series about Laravel Eloquent. You can subscribe to the Laravel tag if you want to be notified when new tutorials are published.

Originally posted on DigitalOcean Community Tutorials
Author: Erika Heidi

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *