0

I have multiple models: User, Track, Tutorial, Chapter, Lesson, & SolvedLesson.

Below is what I've done to for counting each model.

$data = [
    'userCount' => \App\User::count(),
    'userRegisteredToday' => \App\User::whereCreatedAt(date('Y-m-d'))->count(),
    'trackCount' => \App\Models\Track::count(),
    'tutorialCount' => \App\Models\Tutorial::count(),
    'chapterCount' => \App\Models\Chapter::count(),
    'lessonCount' => \App\Models\Lesson::count(),
    'solvedLessonCount' => \App\Models\SolvedLesson::count(),
];

Laravel provides relationships and eager loading to efficiently query. Is there any method to convert the above query into one single query for better performance?

2
  • 2
    Could you also provide the relationship between this models? I think a couple of counts can be avoided.. Commented Jan 4, 2019 at 4:53
  • 1
    what are you trying to achieve. its just the count of each model in dashboard Commented Jan 4, 2019 at 5:23

1 Answer 1

1

The withCount method allows you to count the number of results for model relationships.

Assuming you've defined a one to many relation between the User and SolvedLesson models:

// you can optionally alias the appended count attribute
$users = User::withCount('solvedLessons as solved_count')->get();

// total users
$users->count()

// iterate users to get the number of solved lessons for each
$users->each(function (User $user) {
    // using the alias defined above
    echo $user->solved_count;
});

You're not limited to a single relation either, passing an array will get the count for each relation:

$tracks = Track::withCount(['tutorials', 'users'])->get();

// total tracks
$tracks->count()

// access each relation count per track
$tracks->each(function (Track $track) {
    echo $track->tutorial_count;
    echo $track->user_count;
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.