Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why loadCount() introduced and its actual usage into laravel

Tags:

laravel

I already read doc here : https://github.com/laravel/framework/pull/25997

What i want to know is by using withCount() we were just load count of records instead of getting all relations data.

So by using loadCount() what we can do ?

Please explain in short in simple words. Thanks

like image 616
Vishal Ribdiya Avatar asked Mar 05 '23 09:03

Vishal Ribdiya


1 Answers

loadCount Eloquent Collection Method introduced by the release of Laravel 5.7.10. According to the laravel-news.

loadCount is the ability to load relationship counts on an Eloquent collection. Before this feature, you could only load relationships, but now you can call loadCount() to get counts for all relations.

The pull request illustrates how you could use loadCount() with the following example:

$events = Event::latest()->with('eventable')->paginate();

$groups = $events->map(function ($event) {
    return $event->eventable;
})->groupBy(function ($eventable) {
    return get_class($eventable);
});

$groups[Post::class]->loadCount('comments');
$groups[Comment::class]->loadCount('hearts');

return new EventIndexResponse($events);
like image 106
Inzamam Idrees Avatar answered Mar 17 '23 00:03

Inzamam Idrees