Support the ongoing development of Laravel.io →
Cache Database Eloquent

I'm looking for the most efficient way to get the count of related records from related tables. The best way to understand is to show some code. Here, I'm retrieving a record by id using my repository, along with eager loading related records.

$project = $this->project->findWith($id, ['group', 'expedition.download', 'expedition.subject']);

Relevant relationships:

Project->Expedition = 1:N
Expedition->Subject = 1:N

I only need the number of Subjects in an Expedition so I'm using {{ count($expedition->subject) }} in my view. Right now, I cut down the hits to the database using Cache as a service, but wondered what others do in terms of getting counts from related tables:

public function findWith ($id, $with = array())
{
    $key = md5('project.' . $id . implode(".", $with));

    if ($this->cache->has($key))
    {
        return $this->cache->get($key);
    }

    $project = $this->project->findWith($id, $with);

    $this->cache->put($key, $project);
    
    return $project;
}
Last updated 3 years ago.
0

Hello, I don't deal with cache, but I'm quite good in dealing with databases.
{{ count($expedition->subject) }} is really a bad solution, because $expedition->subject retrieves all the subjects, and count() counts them afterwards. Instead you should ask the database to count that subjects.

{{ $expedition->subjects->count() }}

This is in case that the relations name is 'subjects' instead of 'subject'. I can help you with eager loading, if you need.

Last updated 3 years ago.
0

@Firtzberg - Thanks for the reply. I actually found the solution here: http://laravel.io/forum/05-03-2014-eloquent-get-count-relation

Last updated 3 years ago.
0

Sign in to participate in this thread!

PHPverse

Your banner here too?

rbruhn rbruhn Joined 16 Apr 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.