Skip to content

[Request] Get relationship count without loading all objects #2813

Closed
@dwightwatson

Description

@dwightwatson

I think it would be handy to be able to retrieve the number of objects in a relationship without having to load all the relations from the database as well. If a country has thousands of users it doesn't make much sense loading them in if they aren't being used.

$countries = Country::with('users')->get();

foreach ($countries as $country)
{
     echo $country->name . ' has ' . $country->users->count() . ' users.';
}

Perhaps this syntax could do the trick (assuming most people won't have a counts column in their database).

$countries = Country::withCounts('users')->get();

foreach ($countries as $country)
{
    echo $country->name . ' has ' . $country->counts->users . ' users.';
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions